简体   繁体   中英

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 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 .

You can try using CASE condition in query along with a check on number of rows as the condition.

   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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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