1

我有两张桌子,我已经像下面这样连接起来,向我展示按 id 按降序添加的垫子,效果很好。

SELECT p.* FROM ruj_users_pad 
AS p LEFT JOIN ruj_users
AS u ON p.user_id = u.id 
WHERE u.status !=0 
AND 1 
AND p.status = 1 
GROUP BY p.added_date
DESC LIMIT 0, 20

但是,现在我想检索第三个表,该表也作为“added_date”列与上一个查询结合以显示新的降序。第三个表中的数据是当用户单击以收藏键盘上的当前项目时从按钮生成的。

这是我所拥有的,但它不起作用。

SELECT p.*,f.added_date FROM ruj_users_pad
AS p LEFT JOIN ruj_users 
AS u ON b.user_id=u.id 
LEFT JOIN ruj_users_fave 
AS f ON f.brag_id = u.id 
WHERE u.status !=0 
AND 1 
AND p.status = 1 
GROUP BY f.added_date DESC, b.added_date DESC 
LIMIT 0, 20

结果返回与第一个结果相同。我不明白可能出了什么问题。我希望结果考虑到 ruj_users_fave 中有一个条目,并将其与第一个结果结合起来,将收藏夹放在顶部。

非常感谢您的帮助。

4

1 回答 1

1

UNION这是用于合并两个子查询的问题的解决方案。不是三表全查询,而是两表的精髓来说明概念。我用一张桌子pad和一张桌子likes。第一个子查询使用with选择 padid及其最近的“like” 。请注意,我将列重命名为.MAXGROUP BY idMAX(liked)timestamp

SELECT pad.id, MAX(liked) AS timestamp FROM
pad INNER JOIN likes WHERE likes.pad_id = pad.id
GROUP BY pad.id

另一个子查询选择id尚未被喜欢的 pad ,即喜欢表中不存在该特定 pad 的记录id。在这种情况下,您提到应该使用 pad 的创建日期来确定返回记录的顺序。因此,我们重命名addedtimestamp.

SELECT id, added AS timestamp FROM pad
WHERE NOT EXISTS
  (SELECT liked FROM likes WHERE likes.pad_id = pad.id)

我们现在有两个子查询,它们返回 padid和 the,因此我们可以使用, 然后使用ittimestamp将它们组合成一个结果集。您的组合查询如下所示。UNIONORDERBY timestamp

SELECT combined.id, combined.timestamp FROM
(
  SELECT pad.id, MAX(liked) AS timestamp FROM
    pad INNER JOIN likes WHERE likes.pad_id = pad.id
    GROUP BY pad.id
  UNION
  SELECT id, added AS timestamp FROM pad
    WHERE NOT EXISTS
      (SELECT liked FROM likes WHERE likes.pad_id = pad.id)
)
combined ORDER BY combined.timestamp DESC;
于 2013-01-08T00:16:30.313 回答