我有以下表格:
mysql> select * from `empresas`;
+----+-------+-----------+-------+------------+----------------+
| id | tipo | logotipo | nome | grupo | cnpj |
+----+-------+-----------+-------+------------+----------------+
| 8 | Lazer | troll.jpg | Teste | Pespi Cola | 99999313412312 |
+----+-------+-----------+-------+------------+----------------+
mysql> select * from `empresas_contatos`;
+----+---------+------------+--------------+------------+
| id | empresa | rotulo | email | telefone |
+----+---------+------------+--------------+------------+
| 1 | 8 | Principal | x@xxx.co.co | 5112121212 |
| 2 | 8 | Financeiro | fin@y.net | 5012121212 |
+----+---------+------------+--------------+------------+
我想同时使用左连接,如下所示:
mysql> select `e`.`nome`, `e`.`grupo`, `c`.* from `empresas` `e`
-> left join `empresas_contatos` `c` on
-> `c` . `empresa` = `e` . `id`;
+-------+------------+------+---------+------------+-------------+------------+
| nome | grupo | id | empresa | rotulo | email | telefone |
+-------+------------+------+---------+------------+-------------+------------+
| Teste | Pespi Cola | 1 | 8 | Principal | x@xxx.co.co | 5112121212 |
| Teste | Pespi Cola | 2 | 8 | Financeiro | fin@y.net | 5012121212 |
+-------+------------+------+---------+------------+-------------+------------+
问题在于,以这种方式,查询会重复empresas
字段,例如grupo
, nome
(实际表比示例大!)。
我想知道如何在一行中接收所有数据。结果应该是这样的:
+-------+------------+------+---------+------------+-------------+------------+-------------+------------+
| nome | grupo | id | empresa | rotulo | email1 | telefone1 | email2 | telefone2 |
+-------+------------+------+---------+------------+-------------+------------+-------------+------------+
| Teste | Pespi Cola | 1 | 8 | Principal | x@xxx.co.co | 5112121212 | fin@y.net | 5012121212 |
+-------+------------+------+---------+------------+-------------+------------+-------------+------------+
如果有第三empresas_contatos
行,查询将返回email3
, telefone3
...
我可以使用 GROUP_CONCAT(),但我很想为此找到解决方案。
提前致谢!