我有结构表 prod ID,姓名,关键字,年长。
有必要在年生字段中显示遇到的关键字数量,例如
SELECT yearborn, COUNT(Id) cnt1 FROM prod WHERE keyword='admiral'
GROUP BY yearborn
和
SELECT yearborn, COUNT(Id) cnt2 FROM prod WHERE keyword='captain' GROUP BY yearborn
如何组合这两个查询以获取具有结构
的输出结果表年长,cnt1,cnt2 ?
我试过UNION
SELECT yearborn, COUNT(Id) cnt1 FROM prod WHERE keyword='admiral' GROUP BY yearborn
UNION
SELECT yearborn, COUNT(Id) cnt2 FROM prod WHERE keyword='captain' GROUP BY yearborn
但结果是: 年长,cnt1
请告诉我如何摆脱这种情况。
答案 0 :(得分:1)
您可以在关键字条件上使用SUM()来执行此操作,因为MySQL中的比较结果可以视为0(false)或1(true):
SELECT yearborn, SUM(keyword='admiral') cnt1, SUM(keyword='captain') cnt2 FROM prod GROUP BY yearborn
这也具有仅使用一次表扫描的优势(它比使用联合和子查询更快)。
答案 1 :(得分:1)
SELECT yearborn,
SUM(IF(keyword = 'admiral', 1, 0)) cnt1,
SUM(IF(keyword = 'captain', 1, 0)) cnt2
FROM prod
WHERE keyword = 'admiral'
OR keyword = 'captain'
GROUP BY yearborn
结果将是这样的(当然这是虚构的数据):
+----------+------+------+
| yearborn | cnt1 | cnt2 |
+----------+------+------+
| 2004 | 1233 | 0 |
| 1999 | 0 | 15 |
+----------+------+------+
答案 2 :(得分:0)
SELECT yearborn, COUNT(Id) cnt1, NULL cnt2 FROM prod WHERE keyword='admiral' GROUP BY yearborn
UNION
SELECT yearborn, NULL cnt1, COUNT(Id) cnt2 FROM prod WHERE keyword='captain' GROUP BY yearborn
答案 3 :(得分:0)
怎么样:
SELECT yearborn,SUM(cnt1),SUM(cnt2) FROM
(
SELECT yearborn, COUNT(id) cnt1, 0 cnt2 FROM prod WHERE keyword='admiral'
UNION ALL
SELECT yearborn, 0 cnt1, COUNT(id) cnt2 FROM prod WHERE keyword='captain'
)
GROUP BY yearborn
答案 4 :(得分:0)
嗯,你可以试试这个:
SELECT `yearborn`,
COUNT(`Id`) AS `cnt1`
FROM `prod`
WHERE `keyword` IN ('admiral','captain')
GROUP BY `yearborn`,`keyword`;
编辑:
在GROUP BY语句中添加了keyword
。