2012-11-08 222 views
1

我在MS Access 2010 2個表如下sql查詢連接兩列一個

USERS (u_id, u_name) 
LOAN (l_id, l_from[ref users.u_id], l_to[ref users.u_id], l_amount) 

Users 
+------+--------+ 
| u_id | u_name | 
+------+--------+ 
| 1 | abc | 
| 2 | def | 
+------+--------+ 

Loan 
+-----+--------+------+----------+ 
|l_id | l_from | l_to | l_amount | 
+-----+--------+------+----------+ 
| 1 | 2  | 1 | 100  | 
| 2 | 2  | 1 | 100  | 
| 3 | 1  | 1 | 50  | 
+-----+--------+------+----------+ 

我想選擇貸款的表名而不是數字(l_from & l_to)

select 
    loan.l_id, 
    loan.l_from, 
    users.u_name user_from, 
    loan.l_to, 
    users.u_name as user_to, 
    loan.l_amount 
from loan, users 
where ??? 

回答

3

JOINusers表兩次像這樣:

SELECT 
    l.l_id, 
    fromusers.u_name AS user_from, 
    tousers.u_name AS user_to, 
    l.l_amount 
FROM loan l 
INNER JOIN users fromusers ON l.l_from = fromusers.u_id 
INNER JOIN users tousers ON l.l_to = tousers.u_id 

SQL Fiddle Demo(這是SQL Server 2008,但應該是與ms-access相同的語法,我認爲)

2

只需加入Users表兩次,每次from和to。

SELECT l.l_id, uFrom.u_name AS user_from, 
    uTo.u_name AS user_to, l.l_amount 
FROM LOAN l 
INNER JOIN Users uFrom ON l.l_from = uFrom.u_id 
INNER JOIN Users uTo ON l.l_to = uTo.u_id 
+0

與我在MS訪問,它不工作 –

+0

什麼是「不工作」是什麼意思? –