【问题标题】:How can I join these two complex queries?如何加入这两个复杂的查询?
【发布时间】:2014-09-09 18:30:47
【问题描述】:

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

我想从两个查询中找到Q1.notAnyFewID = Q2.FBID时的结果集

第一季度:

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

第二季度:

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)

当尝试将它们组合在一起时,我似乎总是在加入或子选择或“使用”或在哪里以及如何在正确的地方获得新的东西时搞砸了。

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

【问题讨论】:

  • 为什么不用另一种编程语言来做呢?
  • 因为我不想多次调用数据库(其中一些表会非常大,并且各种单独的查询可能会返回很多结果,所以我不想有循环db-calls)
  • 这些很复杂。你想加入两者的结果?什么关系,IE你会加入哪一栏?没关系,我刚看到你的编辑。感谢清理代码块。
  • @Per 有时两个 db 调用比一个巨大的查询要快得多......而且这样做可能会好得多......你必须做的唯一循环是通过两个查询的结果以匹配共同点......像barmar一样加入它们是在MySQL中做到这一点的一种方法,但是随着查询变得更加复杂并且表大小变得更大,运行查询会慢很多.. . 我以前也遇到过同样的问题。

标签: mysql select join subquery sql-subselect


【解决方案1】:

只需将两个查询作为子查询放在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

【讨论】:

  • 是的,这就是我现在正在尝试的。我想我现在快要上班了。 (我得到了完全相同的代码,但结果似乎有些可疑,但我还必须检查我目前拥有的数据)
猜你喜欢
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多