收集多个字段

时间:2011-09-15 12:59:21

标签: mysql

$q = "SELECT s.id, s.title, s.description,
      (SELECT COUNT(*) FROM ".FORUM_THREADS." t WHERE t.cat_id = s.id) AS topics,
      (SELECT COUNT(*) FROM ".FORUM_REPLIES." r INNER JOIN ".FORUM_THREADS." t ON r.thread_id = t.id 
      WHERE t.cat_id = s.id) AS replies,
      (SELECT r.date FROM ".FORUM_REPLIES." r INNER JOIN ".FORUM_THREADS." t ON r.thread_id = t.id 
      WHERE t.cat_id = s.id ORDER BY r.date DESC LIMIT 1) AS last_post
      FROM ".FORUM_SUBCATEGORIES." s WHERE s.parent = '$catid' AND s.status = '0' ORDER BY s.id";

我正在尝试在查询的以下部分选择多个字段

(SELECT r.date FROM ".FORUM_REPLIES." r INNER JOIN ".FORUM_THREADS." t ON r.thread_id = t.id 
INNER JOIN ".TBL_USERS." u ON u.id = r.author WHERE t.cat_id = s.id ORDER BY r.date DESC LIMIT 1) AS last_post

与r.date一起,我想选择u.username和r.author。

我该怎么做呢?

谢谢!

3 个答案:

答案 0 :(得分:1)

只需将它们添加到SELECT:

(SELECT r.date, r.author, u.username FROM ".FORUM_REPLIES." r INNER JOIN ".FORUM_THREADS." t ON r.thread_id = t.id 
INNER JOIN ".TBL_USERS." u ON u.id = r.author WHERE t.cat_id = s.id ORDER BY r.date DESC LIMIT 1) AS last_post

答案 1 :(得分:0)

OP发表评论后更新:

您需要进行3次单独选择OR(取决于您的数据模型)更改查询,以便last_post查询在FROM子句之后/之后结束(在那里它可以包含尽可能多的列如你所愿)......

答案 2 :(得分:0)

Luke,你有一个集中的select语句,它使用嵌套的select语句来获取计数。您不能依赖嵌套的select语句来计算内连接,因此您必须将它们添加到中央select语句中。

换句话说,加入“.FORUM_REPLIES”。和“你”(不确定那应该代表的是什么)与“.FORUM_SUBCATEGORIES。”。我会为您编写查询,但我不知道如何将子类别与回复和子类别链接到您。