Web Hosting Talk







View Full Version : what is the most efficient way to check if a value exist in 2 tables?


grabmail
01-08-2006, 04:55 PM
right now, my query is

select value from table1 where col = value limit 1 UNION select value from table2 where col = value limit 1


is this the most efficient way to do it?

i tried to select count instead but it doesn't work. I don't know why. Count doesn't seem to work with UNION. When i tried it, it only return the count from table1. table2 is ignored.

ZiDev
01-08-2006, 06:02 PM
I would probably do SELECT t1.col FROM table1 t1, table2 t2 WHERE t1.col = t2.col AND t1.col = value; and if there are rows returned. If there are, the value exists.

grabmail
01-08-2006, 06:06 PM
Oops my mistake. What i meant was to check if a value exist in EITHER of the 2 tables.

Your code will only detect matches in both tables.

ZiDev
01-08-2006, 06:58 PM
Ok, for that you could try SELECT t1.col, t2.col FROM table1 t1, table2 t2 WHERE (t1.col = value OR t2.col = value);

Once again, if one or more rows are returned, the value does exist.

-- HW