mysql如何在两个查询里面进行一次查询?

时间:2013-11-19 02:38:08

标签: mysql sql mysqli case

美好的一天。

Table for test on sqfidle

结果我想要计算type= '0'的行数,并计算type= '1'

的行数

我选择了:

SELECT count(*) FROM Likes WHERE type= '0'

SELECT count(*) FROM Likes WHERE type= '1'

请告诉我如何在两个查询中进行一次查询(合并查询)?

P.S。:还请告诉我如何使结果在一行中有两列,结果在第一列是计数行,其中type ='0',第二列是计数行,其中type ='0'?怎么做到的?它真的?

2 个答案:

答案 0 :(得分:3)

以下内容将这两个查询合并为一个:

SELECT l.type, count(*) AS TotalC
FROM Likes AS l
WHERE l.type = '0' or l.type = '1'
GROUP BY l.type

或者如果您想将结果放在一条记录中,那么您可以使用:

SELECT SUM(CASE l.type WHEN '0' then 1 else 0 end) as Type_0,
  SUM(CASE l.type WHEN '1' then 1 else 0 end) as Type_1
FROM Likes AS l

答案 1 :(得分:0)

如果您希望结果垂直,只需输入UNION

即可输入代码
  

SELECT count(*)FROM喜欢WHERE id ='11001'AND type ='0'UNION

     

SELECT count(*)FROM喜欢WHERE id ='11001'AND type ='1'

如果您希望结果为水平,您可以使用join来加入2结果

SELECT count(*),s1.count1 FROM Likes JOIN (SELECT count(*) as count1 FROM Likes WHERE id = '11001'AND type= '1') as s1 WHERE id = '11001' AND type= '0'

恕我直言.. CMIW

这里是我的sqlfiddle http://sqlfiddle.com/#!2/2ced8/18