通过公共列加入两个MySQL结果

时间:2014-06-28 20:30:09

标签: mysql join

我有一个数据表,格式如下:

| Country1 | Name1 | 9.98 |  
| Country2 | Name2 | 8.98 |  
| Country1 | Name3 | 8.97 |  

我想要表现的是:

| Country  | x<10 | x<9 | etc  
| Country1 |  2   |  1  |   
| Country2 |  1   |  1  |  

我有这个查询,但它将两个结果放在一起(例如,它显示澳大利亚两次)。

SELECT Country,COUNT(*) AS `sub10` FROM `allsub10` WHERE `Time`<10 GROUP BY `Country`

UNION ALL

SELECT Country,COUNT(*) AS `sub9` FROM `allsub10` WHERE `Time`<9 GROUP BY `Country`

ORDER BY `sub10` DESC

如何在保持“国家/地区”的同时选择小于10,然后是9等的所有次数。专栏加入?

3 个答案:

答案 0 :(得分:1)

SELECT Country
, sum(if(`Time`<10,1,0)) as `x<10`
, sum(if(`Time`<9,1,0)) as `x<9`
, sum(if(`Time`<8,1,0)) as `x<8`
 FROM `allsub10`
 GROUP BY `Country`

答案 1 :(得分:0)

UNION将列放在同一位置,因此给定查询的结果将是

| Country  | x < 10  
--row where x < 10
| Country1 |  2   
| Country2 |  1   
--row where x < 9
| Country1 |  1

要在查询中获取不同列中的不同值

SELECT Country, SUM(`sub10`) `sub10`, SUM(`sub9`) `sub9`, ...
FROM   (SELECT Country, COUNT(*) AS `sub10`, 0 AS `sub9`, ... 
        FROM   `allsub10` 
        WHERE  `Time`<10 
        GROUP BY `Country`

        UNION ALL

        SELECT Country, 0 AS `sub10`,COUNT(*) AS `sub9`, ...  
        FROM   `allsub10` 
        WHERE  `Time`<9 
        GROUP BY `Country`) a
GROUP BY Country
ORDER BY `sub10` DESC

或者,如果没有UNION,可以使用CASECOUNT

的主题提供条件
SELECT Country
     , COUNT(CASE WHEN `Time` < 10 THEN 1 ELSE NULL END) AS `sub10`
     , COUNT(CASE WHEN `Time` < 9 THEN 1 ELSE NULL END) AS `sub9`
     , ...  
FROM `allsub10` 
GROUP BY `Country`

答案 2 :(得分:-1)

使用不同?选择不同的国家,...或甚至计数如此计数(不同......