简体   繁体   English

两个表的SQL查询

[英]SQL query for two tables

I will try to explain the problem I'm facing. 我将尝试解释我面临的问题。

I have two tables: Team and Team_contacts 我有两个表:Team和Team_contacts

In the first table there is info like: member_name, member_picture, phone and email 在第一个表中有如下信息:member_name,member_picture,phone和email

In the team_contacts table there are only countries and cities the member is responsible for. 在team_contacts表中,只有成员负责的国家和城市。

So the first table looks like this: 所以第一个表看起来像这样:

member_id: 1
member_name: moonwalker
member_picture: mw.jpg
member_phone: 06xxxxxxxx
member_email: mw@moonwalker.com

The second table looks like this: 第二个表看起来像这样:

member_id: 1
country: USA
city: California

member_id: 1
country: USA
city: Miami

member_id: 1
country: NL
city: Amsterdam

What I need is a query that shows the following: 我需要的是一个显示以下内容的查询:

mw.jpg 
Moonwalker 
Phone: 06xxxxxxxx 
Email: mw@moonwalker.com 
Active in countries: USA, NL 
Active in cities: California, Miami, Amsterdam

I tried different join methods, but nothing seems to work. 我尝试了不同的连接方法,但似乎没有任何工作。 Is there a way to do this with a single query or do I need to use two different queries? 有没有办法通过单个查询执行此操作,还是需要使用两个不同的查询? And how? 如何?

Thanks a lot for the help. 非常感谢您的帮助。

As you are using MySQL you can do: 当您使用MySQL时,您可以:

SELECT team.*,
       GROUP_CONCAT(team_contacts.country SEPARATOR ", ") AS active_in_countries,
       GROUP_CONCAT(team_contacts.city SEPARATOR ", ") AS active_in_cities
FROM team
JOIN team_contacts USING (team_id)
GROUP BY team.member_id

Be aware that the length of the list is limited by group_concat_max_len which is by default 1024, unless you change it using for example: 请注意,列表的长度受group_concat_max_len限制,默认情况下为1024,除非您使用例如更改它:

SET SESSION group_concat_max_len = @@max_allowed_packet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM