我有两个表:searches
和 commonWords
。给定用户输入 Q,如果在 commonWords
中找不到 Q,我想将其插入到 searches
中。
说实话,我完全困惑我该如何做到这一点。如何将 INSERT INTO 与整个 SELECT .. WHERE 结合起来?
我知道我可以通过两个查询来完成:
$db->query('SELECT * FROM commonWords WHERE word = ?', $q);
if ($db->affectedRows() > 0)
$db->query('INSERT INTO searches (search) VALUES (?)', $q);
但是,我想将此操作限制为一个查询。
感谢您的帮助!
最佳答案
如果您想插入 commonWords 中存在的行,请尝试此操作
insert into searches (search) select word from commonWords where word = ?
但是你必须小心,因为你必须为搜索设置唯一索引。 如果没有,您可以插入具有相同值的多行
如果您想在搜索中插入不存在的单词,那么您必须尝试此操作
$db->query('insert into searches (search) select case when count(word) = 0 then \'?\' else NULL end as word from commonWords where word = ?', $q);
关于php - 在与另一个表进行检查后,如何将单词插入到表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7493355/