2012-06-18 193 views
0

我有兩個名爲USERS和EMP的表。從兩個表中選擇DISTINCT值並比較這兩個表

USERS 
------- 

userid | username | useraddress 
-------------------------------- 
    1 | U1  | ADD1 
    2 | U2  | ADD2 
    3 | U3  | ADD3 
    4 | U4  | ADD4 

    EMP 
------- 

empid | empname 
----------------- 
1 | emp1 
2 | emp2 
3 | emp3 

這些都沒有我希望看到這樣的

如果EMPID然後=用戶ID顯示用戶名和useraddress作爲輸出

什麼是該查詢..表?

回答

0

試試這個:

select u.username, u.useraddress 
from EMP e 
inner join USERS u 
on e.empid = u.userid 

但是你可能想顯示所有員工,無論他們是否是用戶,那麼你需要一個左聯接:

select u.username, u.useraddress 
from EMP e 
left join USERS u 
on e.empid = u.userid 

你可以隱瞞事實非匹配的員工將通過這樣做表明NULL

select IFNULL(u.username, 'N/A'), IFNULL(u.useraddress, 'N/A') 
from EMP e 
left join USERS u 
on e.empid = u.userid 
0
select case when e.empid = u.userid 
      then concat(username, ' ', useraddress) 
      else empname 
     end as name 
from users u 
full outer join emp e on e.empid = u.userid 
+0

這是一個稍有不同的結果,你會得到。我想這取決於你如何解釋這個問題:-) – Kerbocat

0
SELECT u.username, u.useraddress 
FROM USERS u INNER JOIN EMP e 
ON u.userid = e.empid; 
0

您還可以使用下面的查詢在MySQL:

SELECT USERS.username, EMP.useraddress FROM USERS,EMP WHERE EMP.id=USERS.userid 
0

綁定都與內部表連接查詢

select username as 'User Name',useraddress as 'User Address' 
from USERS INNER JOIN EMP 
on USERS.userid = EMP.empid; 

但它會顯示所有records.And可以加入這些與查詢左加入用戶在userid或右加入empid