Mysql 从匹配其所有者的pivot检索记录
例如,使用最新的mariaDB版本,我对下面的表结构进行了调整Mysql 从匹配其所有者的pivot检索记录,mysql,mariadb,Mysql,Mariadb,例如,使用最新的mariaDB版本,我对下面的表结构进行了调整 Table A +--------+------+ | id |name | +--------+------+ | 1 | Bob | | 2 | Jane | +--------+------+ Table B +--------+------+ | id |city | +--------+------+ | 1 | abc | | 2 | def | |
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
使用组_concat
创建表临时行1 int、行2 int、行3 int、行4 varchar20、行5 int、行6 varchar20 插入temp 从表3中选择*连接表1上的表1。id=table3.idTable1连接表2上的表2.id=table3.idtable2 选择第1行,第4行, 第6行 =东西 选择“,”+t2.row6 从温度t2开始 其中t1.row1=t2.row1 对于XML路径 ,1, 2, 从温度t1 按t1.row1、t1.row4分组
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