2017-02-20 96 views
-1

我有三個表加入到表中有兩個或多個記錄具有相同的外鍵

用戶

id 
name 

報告

id 
id_user 
comments 

ReportedUser

id 
id_report 
id_user 

我想列出每個報告及其報告特德用戶,但我不知道如何做正確的查詢。

我使用了Inner Join,但它顯示ReportedUser表中的所有記錄,顯示兩次或多次(取決於報告用戶在報告中的報告方式)相同的報告。

我知道我可以在編程語言(PHP)中做到這一點,但我需要使用LIKE運算符等來過濾信息。是否有可能在MySQL中做到這一點?

+0

顯示您的表中的數據與建築,遠遠你試過沒 –

+0

請參閱以下指導如何問一個好的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

回答

0

如果您的數據看起來像這樣

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) 
+0

謝謝!我需要那個。我如何選擇答案作爲解決方案? –

相關問題