MySQL 2查询组合成1个查询

时间:2013-05-30 08:26:36

标签: mysql

所以我必须根据某种类型查询数据库表,并且只想在1个查询中执行。以下是我想要合并的查询:

  1. SELECT usr_id,SUM(币)AS coinppv FROM coin_tbl WHERE coin_type = 1 GROUP BY usr_id
  2. SELECT usr_id,SUM(币)AS来自coin_tbl WHERE coin_type = 3 GROUP BY usr_id
  3. 然后我还希望获得coinppv和coinmly的总和,最后是GROUP BY usr_id。

    我尝试过像ff这样的事情。但我没有得到我想要的结果: (注意:这个例子不包括总结coinppv和coinmly)

    SELECT usr_id,
    (SELECT SUM(coins) FROM `coin_tbl` WHERE coin_type = 1) AS coinppv,
    (SELECT SUM(coins) FROM `coin_tbl` WHERE coin_type = 3) AS coinmly
    FROM `coin_tbl` GROUP BY usr_id
    

    我也参与了JOINing,但我也没有得到我想要的结果。

4 个答案:

答案 0 :(得分:3)

使用In

SELECT usr_id, SUM(coins) 
AS coinppv 
FROM coin_tbl
WHERE coin_type 
IN( 1,3) 
GROUP BY usr_id

答案 1 :(得分:2)

SELECT usr_id, coin_type, SUM(coins)
FROM coin_tbl 
WHERE coin_type = 1 OR coin_type = 3 
GROUP BY usr_id, coin_type

SqlFiddle

上查看此操作

Swapnesh回答(一旦他将编辑它)更好,因为它使用IN子句更易读,如果你必须控制coin_type对“很多”不同类型(比如说五个)或六),但如果只涉及两个coin_type,则没有太大区别

答案 2 :(得分:2)

SELECT usr_id,
       SUM(IF(coin_type = 1,coins,0)) AS coinppv,
       SUM(IF(coin_type = 3,coins,0)) AS coinmly, 
       SUM(coins) AS total
FROM `coin_tbl` 
WHERE coin_type IN (1,3)
GROUP BY usr_id

总数是类型1和3的总和,如果您需要全部

,请删除

答案 3 :(得分:1)

如果你希望每个用户ID在一行中,那么这两个值都应该这样做

SELECT usr_id, SUM(if(coin_type = 1, coins, 0)) AS coinppv, SUM(if(coin_type = 3, coins, 0)) AS coinmly
FROM coin_tbl 
GROUP BY usr_id

如果您想将其作为JOIN进行,并假设您有一个用户表,则可以使用以下内容

SELECT usr_id, IFNULL(Sub1.coinppv, 0), IFNULL(Sub2.coinmly, 0)
FROM user_table 
LEFT OUTER JOIN (SELECT usr_id, SUM(coins) AS coinppv FROM `coin_tbl` WHERE coin_type = 1 GROUP BY usr_id) Sub1 ON coin_tbl.usr_id = Sub1.usr_id
LEFT OUTER JOIN (SELECT usr_id, SUM(coins) AS coinmly FROM `coin_tbl` WHERE coin_type = 3 GROUP BY usr_id) Sub2 ON coin_tbl.usr_id = Sub2.usr_id