开发者

SQL Selecting from a value from two tables

开发者 https://www.devze.com 2023-03-22 13:17 出处:网络
I have the following SQL: SELECT * FROM `table` WHERE `code` = 15510642 I want to modify so that it checks anot开发者_StackOverflowher table as well, so for example:

I have the following SQL:

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

I want to modify so that it checks anot开发者_StackOverflowher table as well, so for example:

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

However that doesn't work. Please help!


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 *)


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消