【问题标题】:sql query select combined select from multiple tablesql查询选择组合从多个表中选择
【发布时间】:2017-02-17 06:58:03
【问题描述】:

我真的不知道标题应该是什么,但这里的问题 我有 2 张桌子(实际上更多)

 table a               table b  
id (pk)| country     id(fk)| Branch
------ | ------      ------|--------
01     | Indonesia   01    | Jakarta
                     01    | Bali

如果我这样做select * from a,b where a.id=b.id 结果将是

id | Country  |Branch
01 | Indonesia|Jakarta
01 | Indonesia|Bali

我希望结果如下所示

id | Country   | Branch
01 | Indonesia | Jakarta,Bali

有可能吗? 我并没有真正尝试做研究(我的意思是搜索),因为我不知道我应该搜索什么关键字

【问题讨论】:

  • 尝试查找 GROUP_CONCAT。
  • 已经在这里回答了:stackoverflow.com/questions/194852/…
  • 谢谢@Scovetta,请发帖作为答案,以便我可以标记已回答
  • 您使用的是哪个 DBMS?
  • 已经解决了,只需要关键字...我正在使用 postgres btw

标签: sql select string-aggregation


【解决方案1】:

使用 MySQL 时,GROUP_CONCAT 是您要查找的函数。

按照上面的请求设置表格:

create table a (
  `id` int(15) auto_increment primary key,
  `country` varchar(200)
);

create table b (
  `id` int(15) not null,
  `branch` varchar(200),
  foreign key(`id`) references a(`id`)
);

insert into a values (1, 'Indonesia');
insert into b values (1, 'Jakarta');
insert into b values (1, 'Bali');

执行查询:

select a.id, 
    a.country, 
    group_concat(distinct b.branch) as 'branch'
from a 
    left join b on a.id=b.id;

输出:

| id |   country |       branch |
|----|-----------|--------------|
|  1 | Indonesia | Jakarta,Bali |

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 2012-11-05
    • 1970-01-01
    • 2021-08-16
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    相关资源
    最近更新 更多