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

时间:2019-04-19 05:22:02

标签: mysql mariadb

使用最新的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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

创建表#temp(row1 int,row2 int,row3 int,row4 varchar(20),row5 int,row6 varchar(20)) 插入#temp 选择* from table3联接Table1上的Table1.id = Table3.idTable1联接table2.id上的table2.id = table3.idtable2

选择第1行,第4行, 第6行 = STUFF((         SELECT','+ t2.row6         从#temp t2         其中t1.row1 = t2.row1         FOR XML路径('')     ),1,2,'') 从#temp t1 GROUP BY t1.row1,t1.row4