从与其所有者匹配的数据透视中检索记录

问题描述 投票:2回答:2

使用最新的mariaDB版本,我有以下表结构(例如修剪)

Table A
+--------+------+
| id     |name  |
+--------+------+
| 1      | Bob  |
| 2      | Jane |
+--------+------+

Table B
+--------+------+
| id     |city  |
+--------+------+
|      1 | abc  |
|      2 | def  |
|      3 | ghi  |
|      4 | jkl  |
+--------+------+

Pivot Table
+-----------+-----------+
| tableA_id | tableB_id |
+-----------+-----------+
|      1    |   1       |
|      1    |   3       |
|      2    |   3       |
|      2    |   4       |
+-----------+-----------+

有没有办法让它从这个输出,或将需要完成PHP吗?

+--------+------+-------+
| id     |name  | city1 |
+--------+------+-------+
| 1      | Bob  |  abc  |
| 1      | Bob  |  ghi  |
| 2      | Jane |  ghi  |
| 2      | Jane |  jkl  |
+--------+------+-------+

对此:

+--------+------+----------+
| id     |name  | cities   |
+--------+------+----------+
| 1      | Bob  |  abc ghi |
| 2      | Jane |  ghi jkl |
+--------+------+----------+

目前使用以下查询

SELECT c.id, c.city1, p.id pid, p.first_name FROM city c
INNER JOIN pivot_tablet piv ON c.id = piv.city_id
INNER JOIN person p ON p.id = piv.person_id
mysql mariadb
2个回答
1
投票

使用group_concat()

SELECT p.id,p.first_name,group_concat(c.city1 SEPARATOR ' ') as cities, 
FROM pivot_tablet piv inner join city ON c.id = piv.city_id
INNER JOIN person p ON p.id = piv.person_id
group by p.id, p.first_name

0
投票

create table #temp(row1 int,row2 int,row3 int,row4 varchar(20),row5 int,row6 varchar(20))insert into #temp select * from table3 join Table1 on Table1.id = Table3.idTable1 join table2 on table2.id = table3.idtable2

选择第1行,第4行,第6行= STUFF((SELECT','+ t2.row 6 FROM #temp t2 WHERE t1.row1 = t2.row1 FOR XML PATH('')),1,2,'') FROM #temp t1 GROUP BY t1.row1,t1.row4

© www.soinside.com 2019 - 2024. All rights reserved.