2017-07-07 64 views
0

我想從兩個相同的表中獲取相同的記錄,但需要檢查。MySql通過檢查從兩個相同的表中獲取一條記錄

我有以下兩個表是相同的:

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_nameaddress是空應該的從記錄table_1 但是再次citytable_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 

試試上面的查詢。

+0

謝謝....工作! – Pranab

0

你可以嘗試這樣的:

SELECT table1.id, table1.enc, table1.first_name, table2.last_name, table1.address, table2.city 
INNER JOIN table2 on table2.id = table1.id 

假設你總是希望從表

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; 
相關問題