期待される結果:
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: