0
我有一個系統,用戶可以報告另一個用戶。選擇同一列兩次+ JOIN
我想獲得以下數據
報告編號|舉報動機|報告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;
問題是子查詢一次給我所有的用戶。它只有一個報告就能創造奇蹟。
的數據庫服務器您使用的? –
PostgreSQL 9.1.15 – Crowley