Mysql联合查询,用名称加入结果

时间:2012-08-02 10:01:47

标签: mysql

SELECT  COUNT(ID) AS RANK1 FROM `db_ranking` WHERE `sid`=2 AND `rank`=1
UNION
SELECT  COUNT(ID) AS RANK2  FROM `db_ranking` WHERE `sid`=2 AND `rank`=2
UNION
SELECT  COUNT(ID) AS RANK3  FROM `db_ranking` WHERE `sid`=2 AND `rank`=3
UNION
SELECT   COUNT(ID)  AS RANK4  FROM `db_ranking` WHERE `sid`=2 AND `rank`=4
UNION
SELECT COUNT(ID) AS RANK5 FROM `db_ranking` WHERE `sid`=2 AND `rank`=5

我想在列中显示每个SELECT结果..

所以我希望有5列,每列都有ID ...

所以它应该是那样的

RANK1 RANK2 RANK3 RANK4 RANK5
  0     3     5     6     7

我现在没有得到它......我不知道为什么

2 个答案:

答案 0 :(得分:1)

以下工作正常..

  select
    (SELECT  COUNT(ID) AS RANK1 FROM `db_ranking` WHERE `sid`=2 AND `rank`=1) as Rank1,
    (SELECT  COUNT(ID) AS RANK2  FROM `db_ranking` WHERE `sid`=2 AND `rank`=2) as rank2,
    (SELECT  COUNT(ID) AS RANK3  FROM `db_ranking` WHERE `sid`=2 AND `rank`=3) as rank3,
    (SELECT   COUNT(ID)  AS RANK4  FROM `db_ranking` WHERE `sid`=2 AND `rank`=4) as rank4,
    (SELECT COUNT(ID) AS RANK5 FROM `db_ranking` WHERE `sid`=2 AND `rank`=5) as rank5
    from dual

答案 1 :(得分:0)

最有效的方法是

SELECT
    SUM(CASE WHEN `rank`=1 THEN 1 ELSE 0 END) as Rank1,
    SUM(CASE WHEN `rank`=2 THEN 1 ELSE 0 END) as Rank2,
    SUM(CASE WHEN `rank`=3 THEN 1 ELSE 0 END) as Rank3,
    SUM(CASE WHEN `rank`=4 THEN 1 ELSE 0 END) as Rank4,
    SUM(CASE WHEN `rank`=5 THEN 1 ELSE 0 END) as Rank5
FROM
    `db_ranking`
WHERE
    `sid`=2