如何在查询中获取每个帖子的作者?

时间:2017-06-04 18:57:50

标签: mysql sql join

这是我当前的查询:

SELECT id,
       subject,
       category cat,
       keywords tags,
       body_html, amount,
       date_time,
       (SELECT COALESCE(sum(vv.value),0)
          FROM votes vv
          WHERE qanda.id = vv.post_id and 15 = vv.table_code) AS total_votes,
       (SELECT COALESCE(sum(vt.total_viewed),0)
          FROM viewed_total vt
          WHERE qanda.id = vt.post_id and 15 = vt.table_code limit 1) AS total_viewed
FROM qanda WHERE type = 0 $query_where
ORDER BY $query_order
LIMIT :j,11;

它提供了一个列表(最多10个案例)的帖子。现在我还需要获得每个帖子的作者姓名。我怎么能这样做?

我的表格结构如下:

// users
+----+--------+-----------------+--------
| id |  name  |      email      |  ....
+----+--------+-----------------+--------

// qanda
+----+------------+-----------------------+-----------+--------
| id |    title   |          body         | author_id |  ....
+----+------------+-----------------------+-----------+--------
-- author_id refers to the id column of users table

我可以添加一个子查询来获取每个帖子的作者姓名。但我认为使用join会更好。

1 个答案:

答案 0 :(得分:1)

可能是你需要一个内部联接用户

  SELECT a.id,
         a.subject,
         a.category cat,
         a.keywords tags,
         a.body_html, 
         a.amount,
         a.date_time,
         u.name 
         (SELECT COALESCE(sum(vv.value),0)
            FROM votes vv
            WHERE qanda.id = vv.post_id and 15 = vv.table_code) AS total_votes,
         (SELECT COALESCE(sum(vt.total_viewed),0)
            FROM viewed_total vt
            WHERE qanda.id = vt.post_id and 15 = vt.table_code limit 1) AS total_viewed
  FROM qanda a 
  INNER JOIN users u on a.id = u.author_id
  WHERE type = 0 $query_where
  ORDER BY $query_order
  LIMIT :j,11;

如果某些帖子没有作者,则必须使用左连接

    SELECT a.id,
         a.subject,
         a.category cat,
         a.keywords tags,
         a.body_html, 
         a.amount,
         a.date_time,
         u.name 
         (SELECT COALESCE(sum(vv.value),0)
            FROM votes vv
            WHERE qanda.id = vv.post_id and 15 = vv.table_code) AS total_votes,
         (SELECT COALESCE(sum(vt.total_viewed),0)
            FROM viewed_total vt
            WHERE qanda.id = vt.post_id and 15 = vt.table_code limit 1) AS total_viewed
  FROM qanda a 
  LEFT JOIN users u on a.id = u.author_id
  WHERE type = 0 $query_where
  ORDER BY $query_order
  LIMIT :j,11;