2012-08-10 69 views
1

我有表如何編寫複雜的查詢與MySQL與表連接

Tasks- id,name

然後我有

userTasks id , task_id , user_id

User - id , name

假設我有在任務表和出那些10個任務我有3個任務userTask

我想這樣的查詢

Select task.id , task.name , STATUS (if(presentInUserTasks),1,0) FROM whatever

STATUS字應該1如果該任務ID存在於usertasks表,以用戶ID,否則它應該是0

使我能夠找到其中的那些事情alreadu在userTask表

回答

4

你正在尋找的EXISTS關鍵字:

SELECT tasks.id, tasks.name, 
    IF(EXISTS(SELECT id 
       FROM userTasks 
       WHERE userTasks.task_id = tasks.id 
       AND userTasks.user_id = @that_user_id) 
     ,1,0) AS STATUS 
FROM tasks 
+0

這一個工作正常 – user17 2012-08-10 06:03:48

1

試試這個:

SELECT b.id, 
     b.name, 
     IF(coalesce(c.Task_ID, -1) = -1, 0, 1) `Status` 
FROM `User` a 
      CROSS JOIN `Task` b 
      LEFT JOIN UserTask c 
       ON a.ID = c.user_ID AND 
        b.ID = c.Task_ID 
Where a.id = 1 

演示:http://sqlfiddle.com/#!2/a22d0/7

0

試試這個:

select T.id , T.name , 
     case when u.task_id is not null then 1 else 0 end as STATUS 
from 
Tasks T left outer join usertasks U 
on T.id=u.task_id 
0

TRY

SELECT t.id,t.name, 
CASE WHEN ut.task_id IS NULL THEN '0' ELSE '1' END 
FROM Tasks t 
LEFT JOIN UserTask ut ON ut.task_id = t.id 
+0

我試過了,但它只返回staus = 1的地方,但我想要任務表中的所有結果,但userTasks中的結果應該有STATUS = 1對於其他應該是0 – user17 2012-08-10 05:51:51

+0

已更新。現在試試 – diEcho 2012-08-10 05:52:30

+0

我認爲你沒有在usertasks上匹配userid,也沒有寫出STATUS字段名 – user17 2012-08-10 06:00:14