检出
| item_id | user_id |
项
| item_id |
我想要一个返回所有项目的查询,如果它存在于特定user_id的签出中,则返回1.否则返回0。
select *
from checkouts
right join items on items.item_id = checkouts.item_id
where checkouts.user_id = 10
问题是它只返回它加入的项目,而不是所有项目。
有什么想法吗?
答案 0 :(得分:2)
怎么样......
SELECT i.item_id, c.user_id, IF(c.user_id IS NULL, 0, 1) AS extra_column
FROM items i
LEFT JOIN checkouts c ON (c.item_id = i.item_id AND c.user_id = 10)
答案 1 :(得分:1)
尝试left outer join
:
select * from items left outer join checkouts using (item_id)
where checkouts.user_id is null or checkouts.user_id = 10
或者您也可以使用:
select * from items i
left outer join checkouts c
on (i.item_id=c.item_id and c.user_id=10)
答案 2 :(得分:1)
尝试right outer join
,例如
select *
from checkouts c
right outer join items i on i.item_id = c.item_id
where c.user_id = 10