gpt4 book ai didi

php select from where multi dual

转载 作者:太空宇宙 更新时间:2023-11-03 11:15:29 26 4
gpt4 key购买 nike

我想向数据库中插入一些数据。在插入的时候,我想先做一个判断:如果table1和table2中不存在title,则插入。这个双关语怎么写?这是正确的吗?或者……谢谢。

mysql_query("
INSERT INTO table1 title
SELECT '".$title."'
FROM dual
WHERE not exists (
SELECT title
FROM table1
WHERE table1.title = '".$title."'
) AND (
SELECT title
FROM table2
WHERE table2.title = '".$title."'
) ");

最佳答案

首先,MySQL没有使用dual表。直接选择值即可。通常要插入到表中,您只需要使用其中之一

INSERT INTO table1(title) SELECT 'something'; # or
INSERT INTO table1(title) VALUES ('something');

但是,下面使用了一个合成表(别名 TT),以便能够在其上使用 LEFT JOIN 连接到其他表。

mysql_query("
INSERT INTO table1(title)
SELECT theTitle
FROM (SELECT '".$title."' theTitle) TT
LEFT JOIN table1 ON table1.title = TT.theTitle
LEFT JOIN table2 ON table2.title = TT.theTitle
WHERE table1.title is null and table2.title is null
");

您也可以只完成 NOT EXISTS 子句

mysql_query("
INSERT INTO table1(title)
SELECT '".$title."'
WHERE NOT EXISTS (SELECT * FROM table1 WHERE title = '".$title."')
AND NOT EXISTS (SELECT * FROM table2 WHERE title = '".$title."')
");

但我更喜欢前者,因为这需要你使用 $title 3 次。

关于php select from where multi dual,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5368171/

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