选择id mysql

时间:2017-08-01 15:20:44

标签: mysql

使用phpmyadmin 我有一张表和一张2张其他表中的2个ID。 一个表是" tb_request"我希望按照它的ID进行分组。另一张表是" extras"我想要2个和,一个如果额外是饮料,一个如果不是。 select和sum工作,但我希望它只为目标ID执行总和。

SELECT tb_request_extra.id_tb_request AS "ID"
(SELECT SUM(amount)
FROM tb_request_extra
INNER JOIN tb_extra
 ON tb_request_extra.id_tb_extra = tb_extra.id
WHERE tb_extra.type="drinks") AS "drinks"
 (Same for extras)
FROM tb_request_extra
 GROUP BY tb_request_extra.id_tb_request

如何仅针对当前ID执行该SUM?结果示例:

ID.      DRINKS.     EXTRAS
1.               3.               5
2.                1.             3. 
3.                  1.             4.  
4.                  0.              0.  

我得到的例子:

ID.       DRINKS.      EXTRAS 
1.              5.                    12
 2.             5.                     12
  3.            5.                    12.  
 4.             5.                     12

继承人的结构 对于重要的事情:tb_request_extra - > id,amount,id_tb_extra,id_tb_request ...... tb_extra-> id,输入

1 个答案:

答案 0 :(得分:-1)

试试这个:

SELECT s1.ID,s1.Drinks,s2.Extras FROM
    (SELECT tb_request_extras.id_tb_request AS 'ID', SUM(amount) AS "Drinks"
    FROM tb_request_extras
    INNER JOIN tb_extras
        ON tb_request_extras.id_tb_extras=tb_extras.id
    INNER JOIN tb_extras_type
        ON tb_extras.tb_id_extras_type=tb_extras_type.id
    WHERE tb_extras_type.extras_type="Bebidas"
    GROUP BY tb_request_extras.id_tb_request) s1
JOIN
    (SELECT  tb_request_extras.id_tb_request AS 'ID', SUM(amount) AS "Extras"
    FROM tb_request_extras
    INNER JOIN tb_extras
        ON tb_request_extras.id_tb_extras=tb_extras.id
    INNER JOIN tb_extras_type
        ON tb_extras.tb_id_extras_type=tb_extras_type.id
    WHERE tb_extras_type.extras_type!="Bebidas"
    GROUP BY tb_request_extras.id_tb_request) s2
ON s1.ID=s2.ID