MySQL 使用 WHERE 子句插入 INTO
MySQL INSERT INTO using the WHERE clause
我正在尝试从我的产品 table 中读取所有 SKU 编号,并将它们作为标签添加到我的产品描述 table 中。
这是我正在使用的查询:
INSERT INTO product_description (tag)
SELECT sku
FROM product p
WHERE p.product_id = pd.product_id; #I don't know where to define pd
这些都不起作用:
INSERT INTO product_description pd (tag)
INSERT INTO product_description (tag) pd
我很难弄清楚 WHERE
子句应该如何构造。我需要确保来自两个 table 的产品 ID 匹配,我也不能给第一个 table 一个别名。
为了澄清我的问题,我实际上是在尝试更新 product_description table 中的现有数据,而不是 add/insert 新行。
我相信您正在寻找更新查询,因为您正在根据与另一个的关系在一个 table 中设置值。
为此,您可以 JOIN
table 一起使用相关列,并相应地设置值:
UPDATE product_description pd
JOIN product p ON p.product_id = pd.product_id
SET pd.tag = p.sku;
这是一个 SQL Fiddle 示例。
INSERT INTO product_description (tag)
(SELECT sku
FROM product p
INNER JOIN product_description pd ON p.product_id = pd.product_id
I'm trying to read all the SKU numbers from my product table and add
those as tags into my product description table.
我读这篇文章是想要这样的东西:
INSERT INTO product_description (tag)
SELECT distinct sku
FROM product p;
如果您不想重复,请确保您在 product_description(tag)
上有唯一的 index/constraint。
您没有给出 table 的结构,但您可能需要产品 ID 和标签:
INSERT INTO product_description (product_id, tag)
SELECT product_id, sku
FROM product p;
我正在尝试从我的产品 table 中读取所有 SKU 编号,并将它们作为标签添加到我的产品描述 table 中。
这是我正在使用的查询:
INSERT INTO product_description (tag)
SELECT sku
FROM product p
WHERE p.product_id = pd.product_id; #I don't know where to define pd
这些都不起作用:
INSERT INTO product_description pd (tag)
INSERT INTO product_description (tag) pd
我很难弄清楚 WHERE
子句应该如何构造。我需要确保来自两个 table 的产品 ID 匹配,我也不能给第一个 table 一个别名。
为了澄清我的问题,我实际上是在尝试更新 product_description table 中的现有数据,而不是 add/insert 新行。
我相信您正在寻找更新查询,因为您正在根据与另一个的关系在一个 table 中设置值。
为此,您可以 JOIN
table 一起使用相关列,并相应地设置值:
UPDATE product_description pd
JOIN product p ON p.product_id = pd.product_id
SET pd.tag = p.sku;
这是一个 SQL Fiddle 示例。
INSERT INTO product_description (tag)
(SELECT sku
FROM product p
INNER JOIN product_description pd ON p.product_id = pd.product_id
I'm trying to read all the SKU numbers from my product table and add those as tags into my product description table.
我读这篇文章是想要这样的东西:
INSERT INTO product_description (tag)
SELECT distinct sku
FROM product p;
如果您不想重复,请确保您在 product_description(tag)
上有唯一的 index/constraint。
您没有给出 table 的结构,但您可能需要产品 ID 和标签:
INSERT INTO product_description (product_id, tag)
SELECT product_id, sku
FROM product p;