简体   繁体   English

如果另一个表中没有记录,则插入到一个表中

[英]Insert into one table if no record exists in another table

How can I club this two queries into one? 我如何将这两个查询合为一体? Insert a record if a record does not exist in another table. 如果另一个表中不存在一条记录,请插入一条记录。 I tried googling but I have only found solutions using joins, not in but here I guess there is no relation between this two tables. 我尝试使用谷歌搜索,但只发现了使用联接的解决方案,但没有发现,但我猜这两个表之间没有关系。 can I still insert into it with a single query 我仍然可以通过单个查询插入其中吗

$res = mysqli_query($con,"SELECT 1 FROM bicds WHERE (bid = $pid] AND uid = $eid)
       OR (bid = $eid AND uid = $pid) LIMIT 1");

if(mysqli_num_rows($res) == 0){
    mysqli_query($con,"Insert into t1 (pid,ust) values ($pid,$ust)");
 }

Any help is greatly appreciated. 任何帮助是极大的赞赏。 Thanks 谢谢

You can do this using insert . . . select 您可以使用insert . . . select来执行此操作insert . . . select insert . . . select insert . . . select : insert . . . select

Insert into t1(pid, ust) 
    select $pid, $ust
    from dual
    where not exists (select 1 from bicds where bid = $pid AND uid = $eid);

This allows you to include a where clause in the insert . 这使您可以在insert包含where子句。

You can try using CASE condition in query along with a check on number of rows as the condition. 您可以尝试在查询中使用CASE条件以及检查行数作为条件。

   select (count *) from FROM bicds WHERE (bid = $pid] AND uid = $eid)
   OR (bid = $eid AND uid = $pid) LIMIT 1")

This will be 0 or NULL if table doesn't exist. 如果表不存在,则为0或NULL。

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

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