我的需要是创建一个查询以返回同一列两次 - 第一列显示所有结果,第二列仅显示带有特殊字符(& 和 ')的名称。
下面我有两个查询,我想将其变成自连接。
SELECT dep
FROM `test_deps`
where dep like "%&%" or dep like "%'%"
退货:
dep
---
CAPS - Dean's Office
Parking & Transportation
SELECT dep
FROM `test_deps`
where dep not like "%&%" or dep not like "%'%"
退货:
dep
---
Admissons
我需要一个返回的查询:
dep1 dep2
------------------------------------
Admissions
CAPS - Dean's Office CAPS - Dean's Office
Parking & Transportation Parking & Transportation
我尝试了这个查询,显然不起作用。
SELECT h1.dep as dep1, h2.dep as dep2
FROM test_deps h1
INNER JOIN test_deps h2
ON h1.id=h2.id
WHERE h1.dep like "%&%"
or h1.dep like "%'%"
or h2.dep not like "%&%"
AND h2.dep not like "%'%"
也许我需要将选择中的
h2.dep as dep
变成查询。
使用条件表达式。
SELECT id,
CASE WHEN dep like "%&%" or dep like "%'%"
THEN dep
END dep1,
CASE WHEN dep not like "%&%" or dep not like "%'%"
THEN dep
END dep2
FROM `test_deps`
-- HAVING dep1 IS NOT NULL AND dep2 IS NOT NULL
;
如果您不需要不符合两个条件的行(例如,
dep = NULL
),则取消注释 HAVING 子句。
如果您需要在输出中使用空字符串而不是 NULL,则将
ELSE ''
添加到两个 CASE。