[英]MySql get one record from two identical tables with a check
我想從兩個相同的表中獲取相同的記錄,但要進行檢查。
我有以下兩個相同的表:
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
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
請嘗試上述查詢。
您可以嘗試類似:
SELECT table1.id, table1.enc, table1.first_name, table2.last_name, table1.address, table2.city
INNER JOIN table2 on table2.id = table1.id
假設您總是要從其中一個表中獲取特定字段
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.