如何在mysql中的主表的单个查询中连接关系表中的值

时间:2017-05-02 02:52:31

标签: mysql

我有三张桌子。一个是包含客户数据的主表,一个是业务类型列表,第三个是与所有相关业务的客户ID的关系。

客户表,即Clients

id | client   | address  | phone   
----------------------------------
1  | John Doe | Address1 | Phone 1
2  | Jane Doe | Address2 | Phone 2
3  | Jack Doe | Address3 | Phone 3

企业类型表,即Businesses

id | business
-----------------
1  | Electrician
2  | Plumber
3  | Home remodel
4  | Bathrooms

关系表,说明哪个客户与哪个企业相关联,即Relations

c_id | b_id
-----------
1    | 3
1    | 4
2    | 2
2    | 4
3    | 1
3    | 2
3    | 4

我需要为每个客户端在一行中选择连接的业务名称,如下所示:

结果:

id | client   | address  | phone   | business
--------------------------------------------------------------------
1  | John Doe | Address1 | Phone 1 | Home remodel, Bathrooms
2  | Jane Doe | Address2 | Phone 2 | Plumber, Bathrooms
3  | Jack Doe | Address3 | Phone 3 | Electrician, Plumber, Bathrooms

单个查询可以实现吗?我尝试了很多concat和group_concat方法但是没有成功。我真的很感激任何想法。

2 个答案:

答案 0 :(得分:1)

是。使用外部联接,GROUP_CONCAT聚合GROUP BY子句。

这样的事情:

SELECT c.id
     , c.client
     , c.address
     , c.phone 
     , GROUP_CONCAT(b.business ORDER BY b.id) AS business 
  FROM `Clients` c
  LEFT
  JOIN `Relations` r
    ON r.c_id = c.id
  LEFT
  JOIN `Businesses` b
    ON b.id = r.b_id
 GROUP
    BY c.id
     , c.client
     , c.address
     , c.phone 

答案 1 :(得分:0)

这样的东西
select * from client
inner join
(
select c.id,group_concat(b.business separator ',') as business
from cleints c
inner join relation r
on c.id=r.c_id
inner join business
on r.b_id=b.id
group by c.id) c1
on c.id=c1.id