如果您的數據看起來像這樣
drop table if exists report;
create table report(id int, name varchar(3));
insert into report values
(1,'abc'),(2,'def'),(3,'ghi');
drop table if exists report_user;
create table report_user (user_id int, report_id int);
insert into report_user values
(1,1),(1,2),
(2,1),
(3,1),(3,3);
你可以使用GROUP_CONCAT
MariaDB [sandbox]> select r.id,r.name report, group_concat(u.username order by u.username asc) useby
-> from report r
-> join report_user ru on ru.report_id = r.id
-> join users u on u.id = ru.user_id
-> group by r.id,r.name
-> ;
+------+--------+---------------+
| id | report | useby |
+------+--------+---------------+
| 1 | abc | Ali,Jane,John |
| 2 | def | John |
| 3 | ghi | Ali |
+------+--------+---------------+
3 rows in set (0.02 sec)
,或者相反
MariaDB [sandbox]> select u.id,u.username, group_concat(r.name order by r.name asc) reportsused
-> from users u
-> join report_user ru on ru.user_id = u.id
-> join report r on r.id = ru.report_id
-> group by u.id,u.username
-> ;
+----+----------+-------------+
| id | username | reportsused |
+----+----------+-------------+
| 1 | John | abc,def |
| 2 | Jane | abc |
| 3 | Ali | abc,ghi |
+----+----------+-------------+
3 rows in set (0.00 sec)
顯示您的表中的數據與建築,遠遠你試過沒 –
請參閱以下指導如何問一個好的SQL相關問題:http://meta.stackoverflo w.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query目前我不明白你的問題,因爲與ReportedUser表的內部連接不會列出每個報告和報告的用戶。請具體說明您嘗試過的內容,嘗試的結果以及最終結果的外觀。 – Shadow