在MySQL中连接数据

时间:2015-04-24 20:44:37

标签: php mysql foreach

我的数据库中有以下数据:

initial   |    word
---------------------------
   E      |    Example1
   E      |    Example2
   N      |    Nextexample1

所需的输出:

E : Example1, Example2
N : Nextexample1

因此,对于每个首字母,它应该显示以该首字母开头的所有单词。

此时输出:

E : Example1
E : Example2
N : Nextexample1

此时我的代码:

<?php
    $pdo = new PDO('mysql:host=...');           
    $sql = "SELECT DISTINCT initial, word FROM `exampletable` ORDER by initial ASC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();

    if($stmtrecords = $stmt->fetchall(PDO::FETCH_ASSOC))
    {

    foreach($stmtrecords as $result)
    {
?>

<?php echo $result['initial'];?> : <?php echo $result['word'];?>

问题:

我完全理解为什么我输错了但不知道如何解决它。我想我需要在foreach循环中使用foreach循环来获得正确的输出,但是如何将单词链接到正确的首字母?

1 个答案:

答案 0 :(得分:4)

您可以使用单个SQL查询执行此操作。

SELECT `initial`, GROUP_CONCAT(`word` SEPARATOR ', ') as `output` 
    FROM `table` GROUP BY `initial` ORDER BY `initial` ASC

在此查询中,您要求MySQLinitial对记录进行分组,并使用GROUP_CONCAT()函数将每个分组聚合为单个行。

使用示例数据

initial | word
--------+--------------
E       | Example1
E       | Example2
Z       | Zebra
N       | NextExample
O       | OtherExample
O       | OtherExample2

会返回:

initial | output
--------+--------------
E       | Example1, Example2
N       | NextExample
O       | OtherExample, OtherExample2
Z       | Zebra