user3205479
user3205479

Reputation: 1533

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

Upvotes: 0

Views: 93

Answers (2)

Ankur Kumar
Ankur Kumar

Reputation: 41

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.

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1271231

You can do this using 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.

Upvotes: 2

Related Questions