简体   繁体   English

MySQL只有在另一个表中存在id时才插入行

[英]Mysql insert a row only if id exist in another table

I have 2 simple table 我有2张简单的桌子

  • table1 -> p_id | table1-> p_id | s_id s_id
  • table2 -> p_id | table2-> p_id | s_id s_id

The two table are same. 这两个表是相同的。 The p_id ai value . p_id ai值

I would like to insert into the table2 a row, but **only if p_id is exist in table1. 我想在table2中插入一行,但是**仅当table1中存在p_id时。 This is possible? 这个有可能? (MySQL) (MySQL)

INSERT INTO table1 (p_id, s_id)
SELECT * FROM (SELECT '100', '2') AS tmp
WHERE NOT EXISTS (SELECT p_id FROM table2 WHERE p_id = '100')
LIMIT 1

You can insert into a table based on any SELECT query. 您可以基于任何SELECT查询将其插入表中。 For example: 例如:

INSERT INTO table2 (p_id, s_id)
SELECT p_id, 2 FROM table1 WHERE p_id = 100;

If there are zero rows in table1 with the specified p_id value, this is a no-op. 如果table1中的零行具有指定的p_id值,则为空。 That is, it inserts zero rows into table2. 也就是说,它将零行插入到table2中。 If there is 1 row in table1 with that p_id value, it inserts into table2. 如果table1中有1行具有该p_id值,它将插入table2中。

No need for LIMIT 1 because if p_id is the primary key then there is guaranteed to be only 1 or 0 rows with the given value. 不需要LIMIT 1因为如果p_id是主键,则保证只有1或0行具有给定值。

尝试这个

Insert into table2 (p_id,s_id) Select p_id,'2' as s_id FROM table1 where p_id=100 LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM