[英]How do I combine two SQL statements into one statement?
I have an INSERT SQL statement where one of the values of the row I insert into the table is the result of another SELECT SQL query. 我有一条INSERT SQL语句,其中我插入表中的行的值之一是另一个SELECT SQL查询的结果。 I was wondering how I can appropriately combine these two statements into one.
我想知道如何将这两个语句合而为一。 Thank you.
谢谢。
The SELECT statement: SELECT语句:
SELECT mpca.creative_attribute_id
FROM media_property_creative_attribute as mpca
WHERE mpca.media_property_id=54
and mpca.media_property_creative_attribute_external_id=101;
The result of this query will be a single value, which I will denote in the next INSERT statement as [creative_attribute_id]. 该查询的结果将是一个值,我将在下一个INSERT语句中将其表示为[creative_attribute_id]。
The INSERT statement: INSERT语句:
INSERT INTO ad_creative_attribute_list (ad_id, creative_attribute_id)
VALUES (12, [creative_attribute_id])
WHERE NOT EXISTS (
SELECT *
FROM ad_creative_attribute_list as acal
WHERE acal.ad_id=12
AND acal.creative_attribute_id=[creative_attribute_id])
Can this be combined into one statement? 可以合并为一个语句吗?
UPDATED 更新
I've updated the query according to the suggestion - hope it will fit your case: 我已根据建议更新了查询-希望它适合您的情况:
INSERT INTO
ad_creative_attribute_list (ad_id, creative_attribute_id)
SELECT
12, mpca.creative_attribute_id
FROM
media_property_creative_attribute as mpca
WHERE
mpca.media_property_id = 54
and mpca.media_property_creative_attribute_external_id = 101
AND NOT EXISTS (SELECT acal.creative_attribute_id
FROM ad_creative_attribute_list as acal
WHERE acal.ad_id = 12
AND mpca.creative_attribute_id = acal.creative_attribute_id);
You can use insert into select syntax 您可以在选择语法中使用插入
Not exists will be correlated sub query 不存在将被关联的子查询
INSERT INTO ad_creative_attribute_list (ad_id, creative_attribute_id)
SELECT 12, mpca.creative_attribute_id
FROM media_property_creative_attribute as mpca
WHERE mpca.media_property_id=54
and mpca.media_property_creative_attribute_external_id=101
And NOT EXISTS (
SELECT 1
FROM ad_creative_attribute_list as acal
WHERE acal.ad_id=12
AND acal.creative_attribute_id= mpca.creative_attribute_id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.