组合2个具有不同列数的select语句,其中1st语句已经在使用JOIN

时间:2013-07-03 20:12:56

标签: mysql sql

我正在尝试将两个具有不同列数的select语句组合在一起。

第一个陈述是:

SELECT s.id, s.date_sent, m.sam_subject, m.sam_msg_id, (SELECT
COUNT(id) FROM tbl_something WHERE schedule_id = s.id) AS
total_recipients FROM tbl_something2 AS s INNER JOIN
tbl_something3 AS m ON s.message_id = m.sam_msg_id ORDER BY
s.date_sent DESC

第二个声明:

SELECT * FROM sms_something4 WHERE status = '0' ORDER BY id DESC

第一个语句的表输出:

id date_sent sam_subject sam_msg_id total_recipients

1 1372880628 e-Newsletter 2 2

输出第二名:

id | subject | sent | failed | date_sent | data_sent | data_failed | message | sam_uid from | select_members | status | from_no
11 | test    |  2   |  0     |  1372881670 | 639176286411,639224588324 | | | | |                             | 0      | 0

关于如何将这两个陈述合并的任何建议?

我的目标输出是

id | subject | sent | failed | date_sent | sam_subject | total_recipients | date_sent for email

sam_msg_id可以忽略。

谢谢。

2 个答案:

答案 0 :(得分:1)

正如AJP所说,你可以这样做:

SELECT s.id, a.subject,a.sent, s.date_sent, m.sam_subject,  
(SELECT COUNT(id) FROM tbl_something WHERE schedule_id = s.id) AS total_recipients 
FROM tbl_something2 AS s 
INNER JOIN tbl_something3 AS m ON s.message_id = m.sam_msg_id 
INNER JOIN
(
SELECT * FROM sms_something4 WHERE status = '0' ORDER BY id DESC
) a on a.subject = m.sam_subject and a.date_sent = s.date_sent
ORDER BY
s.date_sent DESC

答案 1 :(得分:1)

这是基本的,你需要...你可能不得不麻烦拍摄。根据需要添加列。

SELECT *
FROM (
SELECT s.id, s.date_sent, m.sam_subject, m.sam_msg_id, (SELECT COUNT(id) 
                                                    FROM tbl_something 
                                                    WHERE schedule_id = s.id) AS total_recipients 
FROM tbl_something2 AS s 
INNER JOIN tbl_something3 AS m 
    ON s.message_id = m.sam_msg_id 
) as tbl
INNER JOIN (SELECT * FROM sms_something4 WHERE status = '0') as tbl2
    ON tbl2.subject = tbl.sam_subject
    and tbl.date_sent=tbl2.date_sent
    and tbl.total_Recipients = tbl2.sent+ tbl2.failed
ORDER BY tbl.date_sent DESC