MySQL多个结果来自一个语句中的一个表

时间:2017-05-02 19:55:11

标签: mysql select

我试图在两个表中使用多个选择查询:

表1 - > infoTab:

  theType   |          theTime    | theCount 
------------+---------------------+----------
 WithPinIt  | 2017-04-01 13:00:00 | 45
 WithPinIt  | 2017-04-01 13:00:00 | 100
 WithMinIt  | 2017-04-01 13:00:00 | 75
 WithQinIt  | 2017-05-01 13:00:00 | 45
 WithMinIt  | 2017-06-01 13:00:00 | 55

表2 - > defsTab:

   theId  |   theDefs   |   theType
----------+-------------+-------------
1         |  defQs      |  WithQinIt 
1         |  defOs      |  WithOinIt 
1         |  defJs      |  WithJinIt 

我想要的是这样的结果:

          theTime    |  P  |  M 
---------------------+-----+-----
2017-04-01 13:00:00  | 145 | 
2017-04-01 13:00:00  |     | 75 
2017-06-01 13:00:00  |     | 55

到目前为止,我使用了这个查询:

SELECT   
    theTime,   
    (SELECT SUM(theCount) AS pSum FROM infoTab WHERE theType NOT IN (SELECT content FROM defsTab) AND theType LIKE '%P%' GROUP BY theTime) AS Ps,   
    (SELECT SUM(theCount) AS cSum FROM infoTab WHERE theType NOT IN (SELECT content FROM defsTab) AND theType LIKE '%C%' GROUP BY theTime) AS Cs   
FROM infoTab 

但它不起作用......任何帮助?

2 个答案:

答案 0 :(得分:0)

如果您使用CASE

,它应该有效
select
theTime,
sum(
CASE 
WHEN theType like '%P%' THEN theCount
ELSE 0
END) as P,
sum(
CASE 
WHEN theType like '%C%' THEN theCount
ELSE 0
END) as C
from infoTab
where theType NOT IN (SELECT content FROM defsTab)
group by theTime;

答案 1 :(得分:0)

您可以尝试使用CASE这样的语句:

SELECT 
    theTime, 
    SUM( CASE WHEN theType  LIKE '%P%' THEN theCount ELSE 0 END) AS P,
    SUM( CASE WHEN theType  LIKE '%M%' THEN theCount ELSE 0 END) AS M
FROM infoTab    
WHERE theType NOT IN (SELECT theType FROM defsTab)
group by theTime, theType