我想要make sql查询,它会通过检查第一个表上的条件将值从一个表插入另一个表。
我必须检查先前在第一张表中出现的行是否存在。如果不存在则添加否则不添加。
在sql中有查询“insert into select from”模式。
我试过以下查询。但它会插入许多重复项。
INSERT INTO
company_location (company_id, country_id, city_id)
SELECT
ci.company_id, hq_location, hq_city
FROM
company_info ci, company_location cl
WHERE
ci.company_id <> cl.company_id
AND cl.country_id <> ci.hq_location
AND cl.city_id <> ci.hq_city;
重复避免意味着不应再次添加元组(company_id,country_id,city_id)。我必须在这些表格中添加4个表格。
此外,我还要求查询从company_location中删除重复项。即(company_id,country_id,city_id)的组合应该只存在一次。只保留一个元组并删除其他行。
答案 0 :(得分:2)
INSERT INGORE工作。
您还可以正确地重写查询。查询不会按照您的想法执行操作,并且您无法使用18世纪的旧连接语法来执行您想要的操作。
SELECT * FROM t1, t2, t3
是CROSS JOIN,这意味着它采用表t1,t2,t3中所有可能的行组合。通常WHERE包含一些“t1.id = t2.id”条件来限制它并将其转换为INNER JOIN,但是“&lt;&gt;”条件不这样做......
你需要一个合适的LEFT JOIN:
INSERT INTO company_location (company_id,country_id,city_id)
SELECT ci.company_id, hq_location, hq_city
FROM company_info ci,
LEFT JOIN company_location cl ON (
ci.company_id = cl.company_id
AND cl.country_id = ci.hq_location
AND cl.city_id = ci.hq_city
)
WHERE cl.company_id IS NULL
答案 1 :(得分:2)
我希望这个未经测试的脚本有帮助!它只插入一次组合。
INSERT INTO company_location
(company_id,country_id,city_id)
SELECT distinct ci.company_id,
ci.hq_location,
ci.hq_city
FROM company_info ci
WHERE ci.company_id NOT IN
(SELECT cl1.company_id FROM company_location cl1
WHERE cl1.country_id = ci.hq_location
AND cl1.city_id = ci.hq_city
AND cl1.company_id = ci.company_id)
答案 2 :(得分:1)
使用INSERT IGNORE INTO
来自Mysql Docs
Specify IGNORE to ignore rows that would cause duplicate-key violations.
答案 3 :(得分:1)
这是你的第二个问题的答案;查询删除重复的条目: 请注意未经测试的陈述。
解决方案1:
如果您的表中有行ID,则此解决方案才有效。
DELETE FROM company_location
WHERE id NOT IN
(SELECT MAX(cl1.id)
FROM company_location cl1
WHERE cl1.company_id = company_location.company_id
AND cl1.country_id = company_location.country_id
AND cl1.city_id = company_location.city_id)
解决方案2:
这没有row_id。它将所有数据写入临时表。删除第一个表上的内容。并且每次插入一次。 对于该解决方案:如果您在该表上定义了约束,请小心!
CREATE TEMPORARY TABLE tmp_company_location
(
company_id bigint
,country_id bigint
,city_id bigint
);
INSERT INTO tmp_company_location
(company_id,country_id,city_id)
SELECT DISTINCT
company_id
,country_id
,city_id
FROM company_location WHERE 1;
DELETE FROM company_location;
INSERT INTO company_location
SELECT DISTINCT
company_id
,country_id
,city_id
FROM tmp_company_location;