我如何加入这两个复杂的查询?

时间:2014-09-09 18:30:48

标签: mysql select join subquery sql-subselect

我有两个问题,而且它们非常复杂,所以我似乎无法弄清楚如何加入它们。

我希望在两个查询中Q1.notAnyFewID = Q2.FBID找到结果集

Q1:

SELECT DISTINCT notifications.`receiver` AS notAnyFewID
FROM notifications
JOIN 
(SELECT notifications.`ref` AS notRef, notifications.`receiver` AS recI
    FROM notifications
    WHERE notifications.`ref`='tooFewLandings') AS c
ON notifications.`receiver`=c.recI
WHERE notifications.`receiver`!=c.recI

Q2:

SELECT DISTINCT R2PProfiles.id AS r2pID, R2PProfiles.`facebookID` AS FBID
FROM R2PProfiles
LEFT JOIN
      (SELECT COUNT(*) AS Landings, R2PProfiles.facebookID, R2PProfiles.id
            FROM pageTrack         
            JOIN (R2PProfiles)
        ON (pageTrack.inputRefNum = R2PProfiles.id)
WHERE pageTrack.ref='getProfile-Land' AND R2PProfiles.published=2 AND R2PProfiles.`createTime`< NOW()- INTERVAL 24 HOUR GROUP BY R2PProfiles.id) AS h
USING (id) WHERE (Landings < 20)

当试图将它们组合起来时,我似乎总是在连接或子选择中搞砸了或者使用&#34;或者在哪里以及如何使新的地方正确。

使其中一个查询与另一个查询的结果进行比较的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

只需将两个查询作为子查询放在JOIN

SELECT notAnyFewID, r2pID
FROM (SELECT DISTINCT notifications.`receiver` AS notAnyFewID
        FROM notifications
        JOIN 
        (SELECT notifications.`ref` AS notRef, notifications.`receiver` AS recI
            FROM notifications
            WHERE notifications.`ref`='tooFewLandings') AS c
        ON notifications.`receiver`=c.recI
        WHERE notifications.`receiver`!=c.recI) AS q1
JOIN (SELECT DISTINCT R2PProfiles.id AS r2pID, R2PProfiles.`facebookID` AS FBID
        FROM R2PProfiles
        LEFT JOIN
              (SELECT COUNT(*) AS Landings, R2PProfiles.facebookID, R2PProfiles.id
                    FROM pageTrack         
                    JOIN (R2PProfiles)
                ON (pageTrack.inputRefNum = R2PProfiles.id)
        WHERE pageTrack.ref='getProfile-Land' AND R2PProfiles.published=2 AND R2PProfiles.`createTime`< NOW()- INTERVAL 24 HOUR GROUP BY R2PProfiles.id) AS h
        USING (id) WHERE (Landings < 20)) AS q2 
ON q1.notAnyFewID = q2.FBID