Jake
Jake

Reputation: 3486

SQL Selecting from a value from two tables

I have the following SQL:

SELECT * FROM `table` WHERE `code` = 15510642

I want to modify so that it checks another table as well, so for example:

SELECT * FROM `table`,`table2` WHERE `code` = 15510642

However that doesn't work. Please help!

Upvotes: 1

Views: 6241

Answers (3)

Tjekkles
Tjekkles

Reputation: 5602

Work with an inner join.

It will be something like

SELECT * 
FROM Table t INNER JOIN table2 t2 
ON t.Code = t2.Code
WHERE t.Code = 15510642 

I hope this helps!

Tjeu

Upvotes: 0

Bert van Kammen
Bert van Kammen

Reputation: 11

you'll have to join the tables if there's a relation between them.

select * from table as t1, table2 as t2 where t1.code = 15510642 or t2.code=15510642
and t1.id = t2.foreignkeyid

If there's no relation you could try a union, but the fields must match. So only use fields from both tables that match.

select id, somefield, somefield2 from table1 where code = 15510642
union
select id, somefield, somefield2 from table2 where code = 15510642

Upvotes: 1

rabudde
rabudde

Reputation: 7722

Perhaps the poster means UNION because he wants results from both tables?

SELECT * FROM `table` WHERE `code` = 15510642
UNION [ALL]
SELECT * FROM `table2` WHERE `code` = 15510642

Works only when both tables contains same column (or specify them instead *)

Upvotes: 5

Related Questions