Reg H
Reg H

Reputation: 285

mysql subquery problem

I'm scratching my head over a MySQL subquery. And it's only after scratching for more than a couple of hours that I post it here in SO. So here it is:

$query_1 = "SELECT * 
              FROM table_new
             WHERE table_new.NAME NOT IN ('text I know does not exist') ";

$query_2 = "SELECT *
              FROM table_new, 
                   table_old
             WHERE table_new.NAME = table_old.NAME ";

$query_3 = "SELECT * 
              FROM table_new
             WHERE table_new.NAME NOT IN (SELECT * 
                                            FROM table_new, 
                                                 table_old
                                            WHERE table_new.NAME = table_old.NAME) ";

Here's the problem:
$query_1 and $query_2 work. But when I combine them in $query_3, it doesn't work.

Any thoughts?

Upvotes: 0

Views: 440

Answers (1)

OMG Ponies
OMG Ponies

Reputation: 332591

Use:

SELECT * 
  FROM table_new
 WHERE table_new.NAME NOT IN (SELECT table_old.NAME
                                FROM table_old)

Standard SQL only allows one column to column comparison in an IN clause -- you can't use SELECT * in an IN clause because it's not clear which columns values would be compared against in the outer query. However, MySQL is the only one that supports tuples to my knowledge.

There are other ways of writing the query to get equivalent results:

SELECT x.* 
  FROM TABLE_NEW x
 WHERE NOT EXISTS (SELECT NULL
                     FROM TABLE_OLD x
                    WHERE y.NAME = x.NAME)

...or:

   SELECT x.* 
     FROM TABLE_NEW x
LEFT JOIN TABLE_OLD y ON y.NAME = x.NAME
    WHERE y.column_in_table_old IS NULL

Which of those performs best depends on if the columns compared are nullable or not. For more info, see this page.

Upvotes: 3

Related Questions