2011-08-03 139 views
0

定義一個數字 - 當前文章的編號。 還有就是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 

我使用的選擇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 

如何優化這個查詢?

+0

如果您使用authors表和單獨的post_authors表進行標準化的結構,這樣會更容易。 – Jacob

+0

這是Wordpress插件 – newpdv

回答

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=?) 

像這樣的東西應該工作。

+0

第2行的語法錯誤 – newpdv

+0

編輯答案 – Jacob