在使用联盟进行分组之前寻求更有效的订购方式

时间:2013-02-16 09:18:50

标签: php mysql sql join

以下代码适用于我正在寻找的内容但我正在尝试查看是否有更好的方法来创建有效的新闻源。这个新闻源应该选择最近的评论和/或喜欢等,但只展示最新的每个用户(即如果John喜欢2个项目并评论3个项目,只显示最新的评论等。请注意涉及多个UNION。

SELECT * 
FROM (SELECT username, time, comment FROM comments ORDER BY time DESC) AS temp 
GROUP by username 
UNION 
SELECT * 
FROM (SELECT username, time, likes FROM likes ORDER BY time DESC) AS temp 
GROUP BY username 
ORDER BY time DESC
LIMIT 10

1 个答案:

答案 0 :(得分:0)

我认为你可以JOIN username上的两个表,但是这会给你额外的列而不是联合,比如:

SELECT
  c1.username,
  c1.`time` AS CommentTime,
  c1.comment,
  l1.`time` AS LikeTime,
  l1.likes
FROM comments AS c1
INNER JOIN
(
   SELECT username, MAX(`time`) LatestTime
   FROM Comments 
   GROUP BY username
) AS c2  ON c1.username = c2.username
        AND c1.`time`   = c2.LatestTime
INNER JOIN Likes l1 ON c1.username = l2.username
INNER JOIN 
(
   SELECT username, MAX(`time`) LatestTime
   FROM Likes
   GROUP BY username   
) AS l2  ON l1.username = l2.username
        AND l1.`time`   = l2.latestTime
ORDER BY c1.`time` DESC
LIMIT 10;

这会为username提供最新评论,最新likes提供最新评论。