gpt4 book ai didi

mysql - 如果表2中不存在,如何插入到表1中?

转载 作者:可可西里 更新时间:2023-11-01 08:20:49 26 4
gpt4 key购买 nike

我是 mysql 的新手。如果 table2 中不存在记录,我在将记录插入 table1 时遇到问题。我有 2 个表 table1 和 table2 的形式:

table1

dep_id start stop modified deleted
1 23456789 167921525 Yes No
2 34567812 345678145 Yes No
3 32789054 327890546 No No


table2

start stop modified deleted
23456789 167921525 No No
34567823 345678145 No No
32789053 727890546 No No

只有当表 2 的“开始”和“停止”列中不存在值时,我才尝试将值插入到表 1 的开始和停止字段值中。如果它存在,我需要抛出一个错误。这些表没有主键外键关系。我很抱歉不知道正确的语法,但我必须在 mysql 和 PHP 中做这样的事情。

Replace Into into table1 set 'start'=> $start,'stop' => $stop
(select 'start','stop' from table2 where table1.start and table1.stop not in table2.start and table2.stop);

在插入到 table1 之前,如何查询这 2 个表以检查 Table1.start 和 Table1.stop 字段是否与 Table2.start 和 Table2.stop 不匹配?

最佳答案

你可以这样做:

INSERT INTO table1 (start, stop)
SELECT a.*
FROM (SELECT 123456789 start, 234567890 stop) a
LEFT JOIN table2 b ON (a.start,a.stop) IN ((b.start,b.stop))
WHERE b.start IS NULL

123456789234567890 分别是 startstop 的输入值。

然后您可以根据您使用的数据库接口(interface)(PDO、mysqli 等)使用 rowCount 或 num_rows_affected 来检查它。如果为0,则没有插入记录,否则发生插入。


SQLFiddle Demo

关于mysql - 如果表2中不存在,如何插入到表1中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11998585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com