(嵌套的MySQL语句)是否可以使用一个SQL查询实现?有什么改进?

时间:2012-06-16 21:39:06

标签: php mysql sql

是否可以使用一个SQL查询实现?有什么改进?

$query = mysql_query("SELECT id, name FROM fruits WHERE `group`=''");

if ($query) {
    while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
        echo $row['name'];

        $query2   = mysql_query("SELECT name FROM fruits WHERE `group`='{$row['id']}'");

        if (mysql_num_rows($query2)) {
            echo ':';

            while ($row2 = mysql_fetch_array($query2, MYSQL_ASSOC)) {
                echo ' '. $row2['name'] . ',';
            }
            mysql_free_result($query2);

            echo '<br>';
        }
    }
    mysql_free_result($query);
}

结果:

Berries: blueberry, raspberry, strawberry,
Citrus: grapefruit, lime,
Pear

数据库结构SELECT * FROM fruits

id   | group | name
-------------------------
03E7 |       | Berries
0618 | 03E7  | blueberry
051B | 03E7  | raspberry
02AA | 03E7  | strawberry
035F |       | Citrus
07A5 | 035F  | grapefruit
0633 | 035F  | lime
05E1 |       | Pear

2 个答案:

答案 0 :(得分:5)

SELECT a.name as group_name, b.name as item_name
FROM fruits a
LEFT JOIN fruits b
ON b.`group` = a.id
WHERE a.`group` = ''

将为您提供一组看起来像......

的结果行
group_name   item_name
----------------------
Berries      blueberry
Berries      raspberry
...          ...
Citrus       grapefruit
Citrus       lime
...          ...
Pear         NULL

然后,您可以在代码中处理此内容,以生成所需的最终输出。

答案 1 :(得分:0)

完全正常的例子:

<?php

header("Content-Type: text/plain");

$con = mysql_connect("localhost", "root", "");
mysql_select_db("test");

$query = mysql_query("SELECT a.name as `group`, GROUP_CONCAT(b.name ORDER BY b.name SEPARATOR ', ') as name FROM fruits a LEFT JOIN fruits b ON b.`group` = a.id WHERE a.`group` = '' GROUP BY a.name");

if ($query) {
    while ($row = mysql_fetch_array($query)) {
        $group = $row['group'];
        $name  = $row['name'];

        if (isset($name)) {
            echo $group . ': ' . $name . "\n";
        } else  {
            echo $group . "\n";
        }
    }
    mysql_free_result($query);
}
mysql_close($con);

?>

结果:

Berries: blueberry, raspberry, strawberry
Citrus: grapefruit, lime
Pear