Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multi table search

Status
Not open for further replies.

fredsnertz

Vendor
May 21, 2009
2
0
0
US
I have 3 tables (A,B,C) and each has an "id" column. I'm trying to create a query that will tell me if any of the three tables has a row where id is a specific value. I could do this as 3 separate queries but I feel like I should be able to do it as one.

 
Something like this ?
Code:
SELECT * FROM (
SELECT 'A' TableName, ID FROM TableA
UNION SELECT 'B', ID FROM TableB
UNION SELECT 'C', ID FROM TableC
) U
WHERE id='specific value'

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
I am a little confused. In the example 'A', 'B', and 'C' are my table names? What are 'TableA', 'TableB', and 'TableC'? Thanks for the reply.
 
in PHV's example, 'A', 'B', and 'C' are values of a 1-byte "flag" column which identify the table that the rows in the UNION come from

since you are only interested in whether the particular id value is present, and not which table it came from, you can omit those
Code:
SELECT * 
  FROM (
       SELECT ID FROM TableA
       UNION 
       SELECT ID FROM TableB
       UNION 
       SELECT ID FROM TableC
       ) U
 WHERE id = [i]specificvalue[/i]
:)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top