Forum Moderators: open

Message Too Old, No Replies

mysql query to check if this data exists in any of tables

         

LetItBe

9:18 am on Apr 7, 2007 (gmt 0)

10+ Year Member



hi there

i have two mysql tables (for example `table1` and `table2`). there is the same field called `id` in both of these tables. i need a query that checks if variable $id exists in any of these tables at the `id` column.

thanks for an attention.

Birdman

12:58 pm on Apr 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



SELECT * FROM table1 t1, table2 t2 WHERE t1.id=__YOUR_VAL__ OR t2.id=__YOUR_VAL__

That should do it.

FalseDawn

4:11 pm on Apr 7, 2007 (gmt 0)

10+ Year Member



No, that will return a Cartesian product of the 2 tables, which is not what you want.

A Union will do the job:

SELECT 1 FROM DUAL WHERE EXISTS (SELECT * FROM table1 WHERE id=$id)
UNION
SELECT 1 FROM DUAL WHERE EXISTS (SELECT * FROM table2 WHERE id=$id)

...but you may as well just write 2 separate queries

[edited by: FalseDawn at 4:12 pm (utc) on April 7, 2007]