sql查询连接两列与一 [英] sql query joining two columns with one

查看:71
本文介绍了sql查询连接两列与一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ms access 2010中有2个表,如下所示

I have 2 tables in ms access 2010 as below

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)

I want to select names instead of numbers(l_from & l_to) from loan table

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 ???

推荐答案

JOIN users表两次,如下所示:

JOIN the users table two times like so:

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小提琴演示(它是SQL Server 2008,但语法应相同对于ms-access,我认为)

SQL Fiddle Demo (it is SQL Server 2008, but should be the same syntax for ms-access, I think)

这篇关于sql查询连接两列与一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆