将具有多个值的ONE行转换为具有单个值的MULTIPLE列

时间:2018-01-15 12:57:43

标签: mysql sql

我有一个mysql查询

SELECT SUM(idHit = 122791), SUM(idHit = 950521) FROM hits

返回两个值,而不是只有一行有两列:

5, 7

使用mysql语法,我想在两列中获取两个值?像

5
7

这一切,我认为有必要将sql查询转换为子查询,但不确定。请帮助。

2 个答案:

答案 0 :(得分:1)

使用GROUP BY

SELECT idHit, COUNT(*)
FROM t
WHERE idHit IN (122791, 950521)
GROUP BY idHit;

如果您遇到两者可能不存在的问题,那么我建议left join

select ids.idhit, count(t.idhit)
from (select 122791 as idhit union all select 950521) ids left join
     t
     on t.idhit = ids.idhit
group by ids.idhit;

union all是一种有趣的方法。我会把它说成:

SELECT 122791, COUNT(*) FROM hits WHERE idHit = 122791
UNION ALL
SELECT 950521, COUNT(*) FROM hits WHERE idHit = 950521;

仅注意此标准SQL,但如果索引可用,则可以使用索引。

答案 1 :(得分:0)

你可以用UNION

来做
SELECT SUM(idHit = 122791) FROM hits
UNION ALL
SELECT SUM(idHit = 950521) FROM hits