SQL - 从两个不同的表中选择行

时间:2009-02-10 15:04:00

标签: sql mysql

有这个表

Table "Items"

itemID
itemTitle
itemContent

和这个

Table "MyList"

userID
itemID
deleted

如果给定用户ID,我怎样才能从表“Items”中选择所有行并显示“已删除”字段,即使“MyList”中不存在itemID?

查询结果示例:

itemID | itemTitle | deleted | userID
-------------------------------------
1      | Title1    | 1       | 2
2      | Title2    | 0       | 2
3      | Title3    | (null)  | (null)
4      | Title4    | (null)  | (null)

什么是查询,以便我可以得到那个结果?

由于

3 个答案:

答案 0 :(得分:15)

SELECT I.itemID, I.itemTitle, M.deleted
FROM
    Items I
    LEFT OUTER JOIN MyList M ON M.itemID = I.itemID
WHERE M.userID = 9

编辑:根据OP的评论:

SELECT I.itemID, I.itemTitle, M.deleted, M.userID
FROM
    MyList M
    LEFT OUTER JOIN Items I ON I.itemID = M.itemID
WHERE M.userID = 9

答案 1 :(得分:0)

您可以使用outer join

select a.itemId, a.itemTitle, b.deleted
from Items a left outer join MyList b
on a.itemId = b.itemId

答案 2 :(得分:0)

我不确定这是否是最佳方式,但它会返回我想要的内容:

select itemID, itemTitle, deleted, userID
FROM(
SELECT i.id_itemID, i.itemTitle, M.deleted, M.userID
FROM
    MyList M
    right OUTER JOIN Items I ON I.itemID= M.itemID
) as MyTableItems
where itemID = 3 or itemID is null