mysql来自子查询的多个字段

时间:2012-04-08 22:27:51

标签: mysql sql subquery

SELECT 
  (SELECT date FROM forums WHERE topic_id=f.id OR id=f.id ORDER BY id DESC LIMIT 1) as last_reply, 
  f.*, p.id as pid, p.name FROM forums f 
      INNER JOIN players p ON p.id = f.author 
  WHERE f.topic_id=0 ORDER BY f.id DESC

在子查询中,我不仅要返回date字段,还要返回author字段。我怎么能这样做?

看了一下类似的帖子,但不能将它应用到我的。

2 个答案:

答案 0 :(得分:2)

我会这样做:

SELECT 
  (SELECT date FROM forums WHERE topic_id=f.id OR id=f.id ORDER BY id DESC LIMIT 1) as last_reply,
  (SELECT author FROM forums WHERE topic_id=f.id OR id=f.id ORDER BY id DESC LIMIT 1) as last_author,
  f.*, p.id as pid, p.name FROM forums f 
      INNER JOIN players p ON p.id = f.author 
  WHERE f.topic_id=0 ORDER BY f.id DESC

我实际上会再次重复子查询

答案 1 :(得分:0)

也许这样的事情可以帮到你:

SELECT MAX(f.date), f.author
FROM forums f
    INNER JOIN players p ON
        p.id = f.author
WHERE f.tpoic_id = 0
GROUP BY f.author
ORDER BY f.id DESC

但没有桌子结构很难。

祝你好运。