在PHP中连接具有不同ID的表字段

时间:2016-12-20 23:00:00

标签: php mysql sql join

如何只在一个中加入多个具有不同ID的字段? 我有这个MySQL表:

--------------------------------
| *UDH*        |     *Text*     |
--------------------------------
| 050003B90301 | Hi my name is A|
--------------------------------
| 050003B90302 | rmin and I wan |
--------------------------------
| 050003B90303 | t be your frien |
--------------------------------

UDH字段不同但我需要加入文本字段以复制到其他表,结果必须如下:

______________________________________________________________
| UDH          |     Text                                     |
--------------------------------------------------------------
| 1            | Hi my name is Armin and I want be your frien |
---------------------------------------------------------------

你知道一个PHP句子或其他方法来制作这样的东西吗?

1 个答案:

答案 0 :(得分:0)

使用GROUP_CONCAT()。像这样:

select '1' as UDH, group_concat(`Text` separator '') as `Text` from myTable;

如果您需要按UDH列进行排序,可以在group_concat()调用中执行此操作:

select '1' as UDH, group_concat(`Text` order by UDH separator '') as `Text` from myTable;

我刚刚根据您的示例使用以下测试代码验证了此查询:

mysql> create table myTable (UDH varchar(32), `Text` text) engine=innodb;
Query OK, 0 rows affected (0.05 sec)

mysql> insert into myTable (UDH, `Text`) values ('050003B90301', 'Hi my name is A'), ('050003B90302', 'rmin and I wan'), ('050003B90303', 't be your frien');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from myTable;
+--------------+-----------------+
| UDH          | Text            |
+--------------+-----------------+
| 050003B90301 | Hi my name is A |
| 050003B90302 | rmin and I wan  |
| 050003B90303 | t be your frien |
+--------------+-----------------+
3 rows in set (0.00 sec)

mysql> select '1' as UDH, group_concat(`Text` order by UDH separator '') as `Text` from myTable;
+-----+----------------------------------------------+
| UDH | Text                                         |
+-----+----------------------------------------------+
| 1   | Hi my name is Armin and I want be your frien |
+-----+----------------------------------------------+
1 row in set (0.01 sec)