SQL Server查询从同一表中提取两个不同的行

时间:2019-06-17 11:42:40

标签: sql-server

我正在尝试编写一个查询,以从用户表中提取上载器和下载器,但是由于我的WHERE条件只能选择一个用户ID,因此我无法执行此操作。在提供的代码中,在查询中给出了下载者ID(例如10),但由于该上传者的ID存储在tbl_files中名为user_id的列中,因此应该由查询找到该上传者ID。

我尝试编写两个条件,但是它们最终都申请了tbl_files以将上传者作为下载者

SELECT
    tbl_files.id,
    tbl_sessions.[name] as session,
    tbl_users.id as user_id,
    tbl_users.username as downloader
FROM
    tbl_files
INNER JOIN
    tbl_downloads
ON 
    tbl_files.id = tbl_downloads.file_id
INNER JOIN
    tbl_sessions
ON
    tbl_sessions.id = tbl_files.session_id
INNER JOIN
    tbl_users
ON
    tbl_users.id = tbl_downloads.user_id
WHERE tbl_users.id = 10

http://prntscr.com/o2voct

1 个答案:

答案 0 :(得分:0)

我认为您需要使用tbl_users表再添加一个联接以获取上载器详细信息。 试试这个

SELECT
    tbl_files.id,
    tbl_sessions.[name] as session,
    tbl_users.id as user_id,
    tbl_users.username as downloader,
    upld.id as upload_id,
    upld.username as uploader
FROM
    tbl_files
INNER JOIN
    tbl_downloads
ON 
    tbl_files.id = tbl_downloads.file_id
INNER JOIN
    tbl_sessions
ON
    tbl_sessions.id = tbl_files.session_id
INNER JOIN
    tbl_users
ON
    tbl_users.id = tbl_downloads.user_id
INNER JOIN
    tbl_users as upld
ON
    upld.id = tbl_files.user_id
WHERE tbl_users.id = 10