gpt4 book ai didi

php - 如何对 PHP MySQL JOIN 结果进行分组?

转载 作者:行者123 更新时间:2023-11-29 01:44:13 26 4
gpt4 key购买 nike

预期结果:

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



SQL:

CREATE TABLE IF NOT EXISTS `fruits` (
`id` varchar(8) NOT NULL,
`group` varchar(8) NOT NULL,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `fruits` (`id`, `group`, `name`) VALUES
('03E7', '', 'Berries'),
('0618', '03E7', 'blueberry'),
('051B', '03E7', 'raspberry'),
('02AA', '03E7', 'strawberry'),
('035F', '', 'Citrus'),
('07A5', '035F', 'grapefruit'),
('0633', '035F', 'lime'),
('05E1', '', 'Pear');

当前的 PHP:

<?php

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

mysql_connect("localhost", "root", "");
mysql_select_db("test");

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

if ($query) {
while ($row = mysql_fetch_array($query)) {
echo $row['group'] . ': ' . $row['name'] . "\n";
}
mysql_free_result($query);
}

?>

当前结果:

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

最佳答案

SELECT a.name, GROUP_CONCAT(b.name) ... WHERE a.group = '' GROUP BY a.name

总而言之,您需要一个GROUP BY 子句,并且分组的列需要以某种方式聚合(否则您将只会得到一个值)。如果这不起作用,您可以使用获得的结果在 PHP 代码中轻松完成:

$fruits = array();
while ($row = fetch($query)) {
//Can be skipped, but you will get notices
if (!isset($fruits[$row['group']]) {
$fruits[$row['group']] = array();
}
$fruits[$row['group']] = $row['name'];
}

关于php - 如何对 PHP MySQL JOIN 结果进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11233105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com