根据另一个表的内容在MySQL中选择布尔值

时间:2014-05-04 07:05:36

标签: mysql sql

我有以下表格:

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='like'Type='delete'以外的任何其他表格返回第一个表格中的行的多个副本。

我希望这个样本的结果:

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

我希望这是有道理的,并为这么长的问题/解释道歉。

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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