query multiple tables and present data depending on the table

wjh2303

New Member
Messages
139
Reaction score
0
Points
0
I have data (date-stamped) in multiple tables that i would like to present ordered by time. However how the data needs to be presented depends on which table it is from. How can i check which table some data in a union is from and present it accoringly, i.e:
Code:
mysql_query( "(SELECT columns FROM tableA) UNION (SELECT columns FROM tableB) ORDER BY timestamp DESC;

for(all rows){
   if(row is from tableA){
        format like A
   }
   else{
        format like B
    }
}
 

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
My quick and lazy way would be to add a column to each table, call it table_name. Default value 'A' for table A, 'B' for table B and request table_name as part of the UNION. You have your flag.

Let me about on a more elegant way to do it.
 

wjh2303

New Member
Messages
139
Reaction score
0
Points
0
That option did come to mind, but i was hoping someone could point me to an alternative, more elegant (as you phrase it) method. If no-one else provides any input then i shall do that

Thanks
 
Last edited:

descalzo

Grim Squeaker
Community Support
Messages
9,373
Reaction score
326
Points
83
Pretty sure you can do it without adding columns.


PHP:
$q =  "(SELECT 1 as flag, columns FROM tableA) UNION (SELECT 2 as flag, columns FROM tableB) ORDER BY timestamp DESC;" ;

then the first column will be your flag.
 
Top