使用join获取单行中的多个值

时间:2014-06-30 08:11:09

标签: mysql mysqli

我希望在一行中获得与主表匹配的多个值。以下是示例表:

members:
- id
- name
- status

address:
- id
- ref_id(member id)
- address1
- state

contacts:
- id
- ref_id(member id)
- phone
- email

mem_cc
- id
- ref_id(member id)
- category_id
- coverage_id

我正在使用以下查询创建视图以在单个视图中获取所有记录,因此我可以查询该视图以显示列表页面:

SELECT a.id, a.name, a.status, b.address1, b.state, c.phone, d.category_id, d.coverage_id 
FROM members a LEFT JOIN address b 
ON a.id = b.ref_id
LEFT JOIN contacts c 
ON a.id = c.ref_id 
LEFT JOIN mem_cc d 
ON a.id = d.ref_id

现在像会员A这样的情况下订阅3个覆盖范围或3个类别,然后它会向我显示会员A的记录三次,我希望在单一时间内获得会员A记录,涵盖该单行中的所有类别和覆盖范围。问题是如何做到的?

2 个答案:

答案 0 :(得分:2)

我认为在选择类别时需要功能“group_concat”:

select a.id,a.name,a.status,b.address1,b.state,c.phone,
group_concat(d.category_id, d.coverage_id) 
from members a left join address b on a.id = b.ref_id 
left join contacts c on a.id = c.ref_id and left join mem_cc d on a.id = d.ref_id
group by a.id

答案 1 :(得分:0)

正如DMorillo已经说过你将不得不使用分组。通过这种方式,您将获得一个用户记录,然后在不同的列中,您可以根据需要对结果进行分组。 如果您考虑根据您的联接弹出额外的列,那么我不认为这是可能的。看看下面的查询是否适合您的情况。

SELECT a.id,
       a.name,
       a.status, 
       -- This group_concat will produce something like "5th street - Alabama" 
       -- separated with newlines
       -- Check for NULL values since you are using left joins
       GROUP_CONCAT(IFNULL(CONCAT(b.address1, ' - ', b.state), ''))
                    DELIMITER '\n') AS address,
       -- Same goes for phone numbers. Default delimiter is comma.
       GROUP_CONCAT(IFNULL(c.phone, '') DELIMITER ','),
       -- Now you can group your categories.
       GROUP_CONCAT(IFNULL(CONCAT(d.category_id,' ', JOINEDCATEGORYNAME), '') AS category,
       GROUP_CONCAT(IFNULL(CONCAT(d.coverage_id,' ', JOINEDCOVERAGENAME), '') AS coverage
FROM members a 
LEFT JOIN address b ON a.id = b.ref_id
LEFT JOIN contacts c ON a.id = c.ref_id 
LEFT JOIN mem_cc d ON a.id = d.ref_id
-- Here probably your inner joins to categories table and coverage table
GROUP BY a.id