输入两个表格TABLE_A
和TABLE_B
TABLE_A TABLE_B
A_ID | A A_ID | B
1 | a 1 | b
2 | a1 1 | b1
3 | a2 2 | b2
期望输出TABLE C
TABLE_C
A_ID | A | C
3 | a2 | NULL <--- NULL if no matched A_ID in TABLE B
1 | a | b,b1 <--- Concat all rows in TABLE B with ','
2 | a1 | b2
以下代码几乎可以提供上述TABLE_C
,但我希望首先使用C
对NULL
字段DESC
进行排序,然后ORDER BY C IS NULL DESC
。 C
似乎不起作用。 请注意,如果NULL
为C
,则无论字段SELECT
A1.A_ID,
A1.A,
GROUP_CONCAT(B1.B SEPARATOR ',') as 'C'
FROM `TABLE_A` A1
LEFT JOIN `TABLE_B` B1
ON A1.A_ID=B1.A_ID
GROUP BY A1.A_ID, A1.A;
中的值如何,TABLE_C将按A_ID排序。
SELECT
A1.A_ID,
A1.A,
GROUP_CONCAT(B1.B SEPARATOR ',') as 'C'
FROM `TABLE_A` A1
LEFT JOIN `TABLE_B` B1
ON A1.A_ID=B1.A_ID
GROUP BY A1.A_ID, A1.A
ORDER BY C IS NULL DESC, A1.A_ID; <--- Order by C with NULL failed.
以下SQL给出了错误。
d = feedparser.parse('http://feeds.bbci.co.uk/news/rss.xml')
for entry in d.entries:
print(entry.media_thumbnail)
参考&#39; C&#39;不支持(参考群组功能)
答案 0 :(得分:1)
先按ORDER BY Null值,然后按A1.A_ID使用:
SELECT A1.A_ID, A1.A, GROUP_CONCAT(B1.B SEPARATOR ',') as C
FROM `TABLE_A` A1
LEFT JOIN `TABLE_B` B1 ON A1.A_ID=B1.A_ID
GROUP BY A1.A_ID, A1.A
ORDER BY (CASE WHEN GROUP_CONCAT(B1.B SEPARATOR ',') IS NULL then GROUP_CONCAT(B1.B SEPARATOR ',') ELSE A1.A_ID END) ;
关于错误Reference 'C' not supported (reference to group function)
,您应该按'C'
排序,即
ORDER BY 'C' IS NULL DESC, A1.A_ID;
而不是ORDER BY C IS NULL DESC, A1.A_ID;
答案 1 :(得分:0)
您无法按顺序使用Is Null
SELECT
A1.A_ID,
A1.A,
GROUP_CONCAT(B1.B SEPARATOR ',') as 'C'
FROM `TABLE_A` A1
LEFT JOIN `TABLE_B` B1
ON A1.A_ID=B1.A_ID
GROUP BY A1.A_ID, A1.A
ORDER BY C, A1.A_ID DESC