MYSQL:从多个表中返回计数

时间:2014-07-29 20:34:11

标签: mysql sql join return

我遇到以下脚本问题。我正在尝试返回一个表,其中两个邮件的收件人计数同时返回。我知道我所拥有的是错的,但它可能会让你知道我在寻找什么。

SELECT count( mailing_recipient_id ) AS CountA
                    FROM mailing_recipient
                    WHERE `mailing_id` =(
                                        SELECT mailing_id
                                        FROM mailing
                                        WHERE mailing_name = 'Mailing A' ) 
UNION

SELECT COUNT( mailing_recipient_id ) AS CountB
                    FROM mailing_recipient
                    WHERE `mailing_id` =(
                                        SELECT mailing_id
                                        FROM mailing
                                        WHERE mailing_name = 'Mailing B' ); 

非常感谢。

3 个答案:

答案 0 :(得分:1)

您可以使用JOINGROUP BY来获得您正在寻找的结果,如下所示:

SELECT
     m.mailing_name ,
    count(mr.mailing_recipient_id)
FROM mailing_recipient mr
INNER JOIN mailing m
ON mr.mailing_id = m.mailing_id
GROUP BY m.mailing_name
ORDER BY m.mailing_name;

答案 1 :(得分:0)

将它们放入子查询中:

    SELECT SUM(tot.CountA) FROM (

SELECT count( mailing_recipient_id ) AS CountA
                    FROM mailing_recipient
                    WHERE `mailing_id` =(
                                        SELECT mailing_id
                                        FROM mailing
                                        WHERE mailing_name = 'Mailing A' ) 
UNION

SELECT COUNT( mailing_recipient_id ) AS CountA
                    FROM mailing_recipient
                    WHERE `mailing_id` =(
                                        SELECT mailing_id
                                        FROM mailing
                                        WHERE mailing_name = 'Mailing B' ); 

) tot

匹配两个联合查询中的别名和SUM别名。

答案 2 :(得分:0)

SELECT IFNULL(SUM(mailing_name = 'Mailing A'), 0) AS CountA,
       IFNULL(SUM(mailing_name = 'Mailing B'), 0) AS CountB
FROM mailing_recipient mr
JOIN mailing m ON mr.mailing_id = m.mailing_id