2017-06-04 55 views
1

這裏是我當前的查詢:如何獲取查詢中每個帖子的作者?

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

可能是你需要一個內部連接woth用戶

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; 
+0

謝謝。給予好評。你確定'INNER JOIN'嗎?由於有些帖子沒有任何作者。我猜'LEFT JOIN'會更好。我對嗎? –

+0

答覆已更新...左加入,如果不是所有帖子都有用戶 – scaisEdge

相關問題