PDA

View Full Version : Best way to write this query


kevinkhan
03-29-2010, 02:11 PM
Is there a better way of writing this query?

SELECT * FROM `phone_number` WHERE `phone` NOT IN (SELECT `phone` FROM `phone_number_sent`)

This is causing me problems when there is alot of records in my database..

MattF
03-29-2010, 03:00 PM
If phone_number_sent is just a single entry possibly matching the rows phone entry, I'd go with:


$sql = 'SELECT phone FROM phone_number WHERE phone!=phone_number_sent';

bazz
03-29-2010, 07:15 PM
show us your create table statements for both tables. it may be that you haven't indexed the tables sufficiently/correctly.

bazz

Old Pedant
03-29-2010, 07:21 PM
Kevin: It would not cause a lot of problems if you have phone indexed in both tables.

You could also use a LEFT JOIN, thus:

SELECT PN.*
FROM phone_number AS PN LEFT JOIN phone_number_sent AS PNS
ON PN.phone = PNS.phone
WHERE PNS.phone IS NULL;

But if MySQL is any good, it would make the two equivalent in performance. Most important thing would be making sure phone is an index on both tables.