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

时间:2022-05-15 20:22:23

Having this table

有这张桌子

Table "Items"

itemID
itemTitle
itemContent

and this

Table "MyList"

userID
itemID
deleted

how can I select all rows from table "Items" and showing the field "deleted", even if the itemID do not exist in "MyList", given an userID?

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

Example of the query result:

查询结果示例:

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

What would be the query, so that I can get that result?

什么是查询,以便我可以获得该结果?

Thanks

3 个解决方案

#1


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

Edit: Based on OP's comment:

编辑:根据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

#2


I'm not sure if this is the best way of doing this, but it returns what I was looking for:

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

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

#3


You can use outer join:

您可以使用外连接:

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

#1


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

Edit: Based on OP's comment:

编辑:根据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

#2


I'm not sure if this is the best way of doing this, but it returns what I was looking for:

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

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

#3


You can use outer join:

您可以使用外连接:

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