Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select item from one table that is not in another

I have a php page with a variable $lid, and a user with vairable $uid... I need to select some data from 2 tables to fill out the page.

        Table 1                          Table 2
¦----------¦----------¦    ¦----------¦----------¦----------¦
¦    qid   ¦    lid   ¦    ¦   owner  ¦   qid    ¦timestamp ¦
¦----------¦----------¦    ¦----------¦----------¦----------¦

I need to write an SQL statement that gets everything from table 2 where the owner = $uid if the qid is not already listed in table1 with the current pages' $lid.

I tried

SELECT * FROM table_two WHERE qid != (SELECT qid FROM table_one WHERE lid = " . $lid .") AND owner = " . $uid . ";

But had no joy

Any ideas?

like image 680
Chris Headleand Avatar asked Dec 15 '22 20:12

Chris Headleand


1 Answers

This would work:

SELECT * 
FROM table_two 
WHERE qid not in (
    SELECT qid 
    FROM table_one 
    WHERE lid = " . $lid .") 

This will probably perform better:

SELECT T2.* 
FROM table_two t2
LEFT OUTER JOIN table_one T1 ON T2.QID = T1.QID 
    AND T1.LID = " . $lid ."
WHERE T1.qid IS NULL
like image 105
D'Arcy Rittich Avatar answered Jan 06 '23 02:01

D'Arcy Rittich