如何使用mysql连接表来编写复杂查询

时间:2012-08-10 05:34:24

标签: mysql sql database inner-join

我有桌子

Tasks- id,name

然后我有

userTasks id , task_id , user_id

User - id , name

假设我在任务表中有10个任务,其中我在userTask表中有3个任务

我想要这样的查询

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

如果该任务标识出现在该用户标识的usertasks表中,那么STATUS字应为1,否则它应为0

这样我就可以在userTask表中找到哪些任务是alreadu

4 个答案:

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

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

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

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