2013-03-29 49 views
1

兩個表:連接兩個表的主鍵和外鍵具有不同格式

employee 
id name 
1 steve 
2 rob 
3 bell 

position  
position_id employee_id position 
1   e1   manager 
2   e2   seller 
3   e3   director 

的問題是,外鍵的主鍵不同的格式。 我怎樣才能得到結果使用SQL查詢?

name position 
steve manager 
rob seller 
bell director 
+0

是的,這是可能的。你有什麼嘗試? – Aaron

回答

3

你是說你的employee_id在你的position表中總是有一個以「e」爲前綴的嗎?如果是這樣,那麼這應該工作使用CONCAT

select e.name, p.position 
from employee e join position p 
    on p.employee_id = concat('e',e.id) 

SQL Fiddle Demo

+0

您的解決方案像魅力一樣工作,您爲創建SQL Fiddle演示所付出的努力受到高度讚賞!非常感謝你Sgeddes !!!!! – mongotop

+1

@mongotop - np至少,很高興我可以幫忙! – sgeddes

0

CONCAT
功能將幫助您隱式轉換您的數字ID,並在前面加「E」來匹配位置表的EMPLOYEE_ID。然後你可以做一個散列連接來從兩個表中獲得結果。
SQL FIDDLE DEMO


select E.name, 
     P.position 
from Employee E 
inner join Positions P 
    on P.employee_id = concat('e',E.id) 
相關問題