如何向多个引用添加多行

时间:2018-01-17 05:34:56

标签: mysql

假设我的数据库中有2个表。 personperson_purchased_item

id     name       has_purchased
1      Joe        1
2      Mark       0
3      Harry      0
4      Norly      1
5      Freya      0

person_purchased_item

id     person_id     item_code
1      1             1001
2      1             1002
3      1             1003
4      1             1004
5      4             1005

在这种情况下,我想获取特定人物的购买物品,并查询从未购买过的物品。

案例1

查询:

SELECT 
    person.id, person.name, person_purchased_item.item_code 
FROM person INNER JOIN person_purchased_item
    ON person.id = person_purchased_item.person_id
WHERE has_purchased = 1 AND id = 1;

结果:

id     name          item_code
1      Joe           1001
1      Joe           1002
1      Joe           1003
1      Joe           1004

案例2

查询:

SELECT * FROM person WHERE has_purchased <> 1;

结果:

id     name       has_purchased
2      Mark       0
3      Harry      0
5      Freya      0

现在出现了问题:

如何编写一个查询,将所有Joe购买的商品插入到从未购买任何商品的每个人手中?因此,他们每个人都会购买Joe的物品。

1 个答案:

答案 0 :(得分:1)

将Joe的购买记录的交叉连接与尚未购买的所有人一起插入:

INSERT INTO person_purchased_item (person_id, item_code)
SELECT p1.id, p2.item_code
FROM person p1
CROSS JOIN person_purchased_item p2
WHERE
    p1.has_purchased = 0 AND p2.person_id = 1;