2014-05-04 46 views
0

我有以下表格:選擇布爾根據其它表的內容

Name: Posts 

Id Creator Title Body Tags Time 
1 1  Test Test Test 123456789 

Name: Action 

Id Creator Type Target 
1 1  like 1 
2 3  like 1 
3 2  like 1 
4 1  delete 1 

我想從第一個表和一個布爾返回所有的值說明在另一張表WHERE Type='delete'中是否有記錄。

第二張表中的Target字段對應於第一張表中的Id

我有以下查詢(這是行不通的)。一方面,它爲Action表中的每個對應行返回行的一個實例,即使對於'delete'以外的行爲也是如此。

SELECT `Posts`.*, IF(`Action`.`Type`='deleted',1,0) AS "Deleted" 
FROM `Posts` JOIN 
    `Action` ON `Action`.`Target` = `Posts`.`Id` 
ORDER BY `Id` DESC; 

我不希望在第一個錶行的多個副本Type='delete'返回Type='like'或任何其他人分開。

我期望從這一樣本的結果:

Id Creator Title Body Tags Time Deleted 
1 1  Test Test Test 123456789 1 

我希望這是有道理的,我的這種冗長的問題/解釋道歉。

+0

任何樣品和期望的結果集? –

+1

@MKhalidJunaid增加:) – ThePixelPony

+0

你想要的結果集也需要 –

回答

0
SELECT Posts.*, IF(Action.Id IS NULL,0,1) as Deleted 
FROM Posts 
LEFT JOIN Action 
ON Action.Target = Posts.Id and Type='delete' 

如果你不關心性能比較

SELECT Posts.*, 
     exists 
    (SELECT 1 
    FROM Action 
    WHERE Target = Posts.Id 
    AND TYPE='delete') AS Deleted 
FROM Posts 
0

正如你可以看到你正在使用deleted而在數據集中是delete

SELECT `Posts`.*, 
     IF(`Action`.`Type`='delete',1,0) AS "Deleted" 
FROM `Posts` 
JOIN `Action` ON `Action`.`Target` = `Posts`.`Id` 
WHERE `Action`.`Type` != 'like' 
ORDER BY `Id` DESC; 
+0

這排除了第一個表中其他表中具有「like」操作的所有結果。我仍然希望選擇那些,但是隻用'Deleted = 0'。但是,如果我從中刪除了'WHERE'子句,它會爲每個''like''返回重複的行。 – ThePixelPony