1

我有桌子

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

1如果该任务 ID 存在于该用户 ID 的 usertasks 表中,则STATUS 字应该是,否则它应该是0

这样我就可以在 userTask 表中找到哪些任务已经存在

4

4 回答 4

3

您正在寻找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
于 2012-08-10T05:38:41.800 回答
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

于 2012-08-10T05:40:25.633 回答
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
于 2012-08-10T05:41:00.160 回答
0

尝试

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
于 2012-08-10T05:42:18.353 回答