預期結果:如何在PHP MySQL JOIN結果上進行分組?
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:
默認SEPARATOR是','沒有空格,您想要將其更改爲GROUP_CONCAT(b.name SEPARATOR',') –
感謝@ExplosionPills發現我'GROUP_CONCAT'!你的代碼段不起作用,沒有這樣一個PHP函數'fetch',爲什麼我需要'array'。我只是通過工作示例添加了我的答案。 @PugganSe,感謝發佈關於'SEPARATOR'! – Binyamin
'fetch'是速記..你應該用一點創造力來推斷你需要的答案。 –