...

View Full Version : Selecting from two tables



maghiel
03-07-2007, 12:21 PM
This is really a stupid question but i just can't think today lol.

i got two tables, let's say
tbl1
-----
id
title
id2
----

tbl2
----
id
title
id2
----

Now i need to know if there's data in either tables with id2 is let's say 5

SELECT * FROM `tbl1`, `tbl2` WHERE `tbl1`.`id2` = '5' OR `tbl2`.`id2` = '5';

won't work.
quite logical, but again, i can't think today.
can anyone help? :)

guelphdad
03-07-2007, 03:14 PM
You want a UNION or UNION ALL.

UNION will give you results from the two tables but eliminate duplicate rows, the UNION ALL will return both tables, duplicates included.



select
id,
title,
id2
FROM table1
where id2 = 5
UNION ALL
select
id,
title,
id2
FROM table2
where id2 = 5

maghiel
03-07-2007, 04:23 PM
thnx m8 that did the trick :)

guelphdad
03-07-2007, 04:56 PM
oh and one last thing, in case you need to know what table the results came from you can use this trick:



select
'table 1' as tablename,
id,
title,
id2
FROM table1
where id2 = 5
UNION ALL
select
'table 2',
id,
title,
id2
FROM table2
where id2 = 5

maghiel
03-08-2007, 12:52 PM
thnx m8 :)

didnt need to know that though, there were two categories having there own table in which users could place records, but in one of the two categories a categorie-title had to be made first.

but thnx :)

guelphdad
03-08-2007, 02:46 PM
You should have a single table in my opinion with either NULL or a default value for the category title.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum