选择相同的列两次+ JOIN

时间:2015-05-19 14:33:18

标签: database postgresql

我有一个用户可以报告其他用户的系统。

我想获得以下数据

报告ID |报告动机| report owner_id |报告所有者用户名|报告的用户ID |报告用户用户名|创建日期

报告

id SERIAL PRIMARY KEY,
owner_id INTEGER REFERENCES Registered(user_id),
creation_date TIMESTAMP NOT NULL,
motive VARCHAR(50) DEFAULT 'TOA Violation' NOT NULL
active BOOLEAN DEFAULT TRUE

Reporteduser

report_id INTEGER REFERENCES Report(id),
user_id INTEGER REFERENCES Registered(user_id),
PRIMARY KEY(report_id, user_id)

id SERIAL PRIMARY KEY,
username VARCHAR(20) UNIQUE NOT NULL,
password VARCHAR(50) NOT NULL,
email VARCHAR(50) UNIQUE NOT NULL
creation_date TIMESTAMP NOT NULL

我写了

SELECT DISTINCT report.id, report.owner_id AS source_id, reporteduser.user_id AS target_id, report.motive, report.creation_date,
(SELECT person.username
 FROM person
 JOIN reporteduser
 ON person.id = reporteduser.user_id) AS target_user,
(SELECT person.username
 FROM person
 JOIN report
 ON person.id = report.owner_id) AS source_user
FROM report
JOIN person
ON report.owner_id = person.id
JOIN reporteduser
ON reporteduser.report_id = report.id
WHERE report.active = TRUE;

问题是子查询一次性给了我所有用户。只用一份报告就可以创造奇迹。

1 个答案:

答案 0 :(得分:1)

你不需要所有这些子查询,尝试这样的事情:

select r.*, o.name as owner_name, p.name as reported_name
from report r
join person o on o.id = r.owner_id
join reporteduser ru on ru.report_id = r.id
join person p on p.id = ru.user_id
where r.active = true