这似乎是最难搜索的东西 - 我可以找到很多"如何在两个表中找到空箱",或者如何为非sqlite找到空,但......
如何找到尚未订购商品的用户?
所以,如果......
...然后我想返回一行:
user.name item.name
--------- ---------
Danny nail
我可以搜索一下吗?在sqlite?
答案 0 :(得分:0)
如果我正确理解您的问题,您想要找到每个用户未订购的每件商品吗?这可以通过以下查询来完成:
SELECT
user.name AS user_name,
item.name AS item_name
-- Get all users and items.
FROM user
CROSS JOIN item
-- Exclude items that users have ordered.
WHERE NOT EXISTS (
SELECT *
FROM item_user
WHERE item_user.item_id = item.id
AND item_user.user_id = user.id
);
这会产生:
user_name | item_name
----------+----------
'Danny' | 'nail'
用于构造表的查询:
CREATE TABLE item (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL
);
INSERT INTO item (name)
VALUES ('hammer'), ('nail');
CREATE TABLE user (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL
);
INSERT INTO user (name)
VALUES ('Bob'), ('Jane'), ('Danny');
CREATE TABLE item_user (
item_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
FOREIGN KEY (item_id) REFERENCES item (id),
FOREIGN KEY (user_id) REFERENCES user (id)
);
INSERT INTO item_user (user_id, item_id)
VALUES
(1, 1), -- Bob, hammer
(1, 2), -- Bob, nail
(2, 1), -- Jane, hammer
(2, 2), -- Jane, nail
(3, 1); -- Danny, hammer