2017-02-20 88 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

谢谢!我需要那个。我如何选择答案作为解决方案? –

相关问题