选择具有特定行的作者

时间:2011-08-03 11:10:59

标签: mysql

定义一个数字 - 当前文章的编号。 有一个authors的表格:

id | post_id | autor

需要选择作者列表,在本文中添加一个指示给定作者的列。

示例:

id | post_id | autor
 1      33      Jacob
 2      35      Mike
 3      31      John
 4      35      Jacob
 5      33      Andrew

需要获得第35条:

autor | use
Jacob    1
Mike     1
John     0
Andrew   0

我对select autors使用查询:

SELECT a.`autor`, (
 SELECT count(*) as `count`
 FROM `autors` 
 WHERE `post_id`=35 AND `autor`=a.autor 
)
FROM `autors` a
GROUP BY `autor`
ORDER BY `autor` DESC

如何优化此查询?

1 个答案:

答案 0 :(得分:0)

SELECT a1.autor, 
       (CASE WHEN a2.post_id IS NULL THEN 0 ELSE 1) AS `use`
FROM (SELECT DISTINCT * 
      FROM `autors`    
      ORDER BY `autor` DESC) AS a1
LEFT JOIN autors AS a2 ON (a1.autor=a2.autor AND a2.post_id=?)

这样的事情应该有效。