MySQL左连接和第二次选择计数

时间:2012-04-02 14:06:51

标签: mysql left-join multiple-tables

我有以下表格:

网页

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| page_id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| type       | varchar(20)  | NO   |     | NULL    |                |
| parent_id  | int(11)      | NO   |     | NULL    |                |
| title      | varchar(255) | NO   | MUL | NULL    |                |
| text       | longtext     | NO   | MUL | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

自定义

+---------+------------------+------+-----+---------+-------+
| Field   | Type             | Null | Key | Default | Extra |
+---------+------------------+------+-----+---------+-------+
| page_id | int(10) unsigned | NO   | PRI | NULL    |       |
| key     | varchar(255)     | NO   | PRI | NULL    |       |
| value   | longtext         | NO   |     | NULL    |       |
+---------+------------------+------+-----+---------+-------+

使用以下查询,我获取表格页面type = 'questions'的所有条目,并从表格自定义中获取值key = 'votes'

这里的问题是这个。在表格页面中,我想用type = 'comments' AND parent_id = 'page_id'

计算所有条目
SELECT * FROM pages AS P  
LEFT JOIN custom AS C
    ON P.page_id = C.page_id AND  
        C.key = 'votes'
WHERE  
    P.type = 'questions'  
ORDER BY P.date DESC, C.value DESC

问题是我必须在某处SELECT COUNT(*) AS posts_count FROM pages WHERE page_id = parent_id插入,并且 posts_count 中的值必须在查询中可用,因为我想按注释顺序对条目进行排序并在此之后来自表自定义

的投票

1 个答案:

答案 0 :(得分:0)

您似乎可以使用子查询来获得此结果:

SELECT p1.page_id,
  p1.type,
  p1.parent_id,
  p1.title,
  p1.text,
  Coalesce(p2.TotalComments, 0) TotalComments,
  c.key,
  c.value
FROM pages AS P1
LEFT JOIN
(
  select count(*) TotalComments, parent_id
  from pages
  where type = 'comments'
  group by parent_id
) p2
  on p1.parent_id = p2.parent_id
LEFT JOIN custom AS C
  ON P1.page_id = C.page_id 
  AND C.key = 'votes'
WHERE P.type = 'questions'  
ORDER BY P1.date DESC, C.value DESC