我希望从两个相同的表中获取相同的记录,但需要检查。
我有两个完全相同的表:
table_1
id | enc | first_name | last_name | address | city
1 | 1001 | John | Doe | abc |
table_2
id | enc | first_name | last_name | address | city
1 | 1001 | | Doe | | xyz
我想从table_2获取记录,但由于first_name
和address
为空,因此它应该来自记录table_1
但city
中的table_1
再次为空,因此它会从table_2
获取记录
我已经尝试过像这样的工会:
(SELECT * from `table_1` where `id` = `1)
UNION
(SELECT * from `table_2` where `id` = `1)
但它提供了表中的记录。我想只使用这两个表的一条记录:
id | enc | first_name | last_name | address | city
1 | 1001 | John | Doe | abc | xyz
答案 0 :(得分:1)
SELECT IFNULL(T1.id,T2.ID) ID,IFNULL(T1.enc,T2.ENC)ENC,IFNULL(T1.first_name,T2.first_name)first_name , IFNULL(T1.last_name ,T2.last_name )last_name ,
IFNULL(T1.address ,T2.address )address ,
IFNULL(T1.city,T2.city)address
from `table_1` T1
INNER JOIN `table_2` T2 ON T1.ID=T2.ID
尝试以上查询。
答案 1 :(得分:0)
您可以尝试以下方式:
SELECT table1.id, table1.enc, table1.first_name, table2.last_name, table1.address, table2.city
INNER JOIN table2 on table2.id = table1.id
假设您总是希望从其中一个表中获取特定字段
答案 2 :(得分:0)
SELECT table_2.id,table_2.enc,table_1.first_name,table_2.last_name,table_1.address,table_2.city
FROM table_2,table_1
WHERE table_2.id=table_1.id
AND table_2.id=1;