homepage Welcome to WebmasterWorld Guest from 107.22.45.61
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld
Home / Forums Index / Code, Content, and Presentation / Databases
Forum Library, Charter, Moderators: physics

Databases Forum

    
Identify source table name when using UNION
I'm using UNION too query 3 tables but need to identify records table.
snowweb




msg:3586948
 11:20 am on Feb 28, 2008 (gmt 0)

I'm running the query below:

$query
="(SELECT id, col2, col3 FROM table1 WHERE user_id = $_SESSION[user_id])
UNION ALL
(SELECT id, col2, col3 FROM table2 WHERE user_id = $_SESSION[user_id])
UNION ALL
(SELECT id, col2, col3 FROM table3 WHERE user_id = $_SESSION[user_id])";

The problem is that I need to be able to identify which table each result originated from.

The only way I can figure out is to do it as 3 separate queries and then add a 4th column to the query result array with the name of the table in it and then later merge that array with the other two.

Seems too messy and I'm sure some of you clever guys have got a much better way!

I hope you can help me. Thanks in advance.

peter

 

syber




msg:3587009
 1:01 pm on Feb 28, 2008 (gmt 0)


SELECT id, col2, col3, 'table1' AS source
FROM table1 WHERE user_id = $_SESSION[user_id])
UNION ALL
(SELECT id, col2, col3, 'table2'
FROM table2 WHERE user_id = $_SESSION[user_id])
UNION ALL
(SELECT id, col2, col3, 'table3'
FROM table3 WHERE user_id = $_SESSION[user_id]

snowweb




msg:3587041
 2:02 pm on Feb 28, 2008 (gmt 0)

cool!

Thanks buddy!

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / Databases
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved