来自UNION SUBSELECT的MySQL字段

时间:2011-11-30 13:37:48

标签: mysql sql select union subquery

我的数据库包含以下表格:

  • t1:博客文章
  • t2:每篇博文的附加表
  • t3:博客文章的英文评论
  • t4:西班牙语对博客文章的评论

我有以下用例: 我需要获取每篇博客帖子的最新评论的ID以及博客帖子本身。最新评论可能在t3或t4表中。

我提出了以下sql,但它没有按预期工作。

SELECT t1.id,
t1.one, 
t1.two, 
(
    SELECT id FROM (
        (SELECT * FROM t3 where t3.refid = t1.id) 
        UNION (SELECT * FROM t4 where t4.refid = t1.id) 
        ORDER BY datetime ASC LIMIT 1
    ) AS tempTable) 
AS someValue
FROM t1 
LEFT JOIN t2 ON (t1.id = t2.id) 
WHERE t1.otherid=42 AND t1.somefield > 0 
ORDER BY t1.someOtherField 
LIMIT 5

非常感谢任何关于if和/或如何实现这一点的提示,谢谢!

2 个答案:

答案 0 :(得分:0)

您需要将包含t3和t4最新注释的表编译到表d中 然后还将两个结果合并到评论表c中 此c只会保留一个条目,即最新的ID,来自t3或来自t4

c.t会告诉您从哪个表中得到回复;

SELECT t1.*, 
       t2.*, 
       c.id AS cid, 
       c.dt AS dt, 
       c.t  AS t 
FROM   t1 
       LEFT JOIN t2 
         ON ( t1.id = t2.id ) 
       LEFT JOIN (SELECT d.id, 
                         Max(d.dt) AS dt, 
                         d.refid, 
                         d.t       AS t 
                  FROM   (SELECT t3.id, 
                                 Max(DATETIME) AS dt, 
                                 t3.refid, 
                                 3             AS t 
                          FROM   t3 
                          GROUP  BY t3.refid 
                          UNION ALL 
                          SELECT t4.id, 
                                 Max(DATETIME) AS dt, 
                                 t4.refid, 
                                 4             AS t 
                          FROM   t4 
                          GROUP  BY t4.refid) d 
                  GROUP  BY d.refid) c 
         ON c.refid = t1.id; 

答案 1 :(得分:0)

首先尝试此查询,它应该返回t3和t4的最新评论 -

SELECT t_comments1.* FROM (SELECT * FROM t3 UNION SELECT * FROM t4) t_comments1
  JOIN (SELECT refid, MAX(datetime) max_datetime FROM (SELECT * FROM t3 UNION SELECT * FROM t4) t GROUP BY t.refid) t_comments2
    ON t_comments1.refid = t_comments2.refid AND t_comments1.datetime = t_comments2.max_datetime;

如果没问题,那么让我们将此查询与t1表结合起来 -

SELECT t1.*, t_comments.* FROM t1
  LEFT JOIN (
    SELECT t_comments1.* FROM (SELECT * FROM t3 UNION SELECT * FROM t4) t_comments1
      JOIN (SELECT refid, MAX(datetime) max_datetime FROM (SELECT * FROM t3 UNION SELECT * FROM t4) t GROUP BY t.refid) t_comments2
        ON t_comments1.refid = t_comments2.refid AND t_comments1.datetime = t_comments2.max_datetime
  ) t_comments
  ON t1.id = t_comments.refid;