我想在查询中找到结果。问题是我使用IF
语句根据该条目的另一列的值来对结果进行别名化。
这很好用
SELECT town
IF(is_found = 0, name, null) as not_found,
IF(is_found = 1, name, null) as found
FROM listing
但是如果我想按城镇分组我的结果,我需要连接名单列表的结果。
我试过了:
SELECT town
GROUP_CONCAT(IF(is_found = 0, name, null) as not_found) as missing_list,
GROUP_CONCAT(IF(is_found = 1, name, null) as found) as found_list
FROM listing
我收到了语法错误。
如何生成这样的连续列表,其中结果以IF语句为条件。
答案 0 :(得分:2)
as
不会进入if
。所以你可以这样做:
SELECT town,
GROUP_CONCAT(IF(is_found = 0, name, null)) as missing_list,
GROUP_CONCAT(IF(is_found = 1, name, null)) as found_list
FROM listing
GROUP BY town;
我更喜欢case
而不是if
(因为它几乎在所有数据库中都是标准的):
SELECT town,
GROUP_CONCAT(CASE WHEN is_found = 0 THEN name END) as missing_list,
GROUP_CONCAT(CASE WHEN is_found = 1 THEN name END) as found_list
FROM listing
GROUP BY town;