2012-06-27 82 views
2

預期結果:如何在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: 

回答

1

感謝@ExplosionPills發現我關於MySQL GROUP_CONCAT我已經更新了我的代碼片段:

<?php 

$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); 
} 

?> 

SQL結果:

顯示行0 - 2(3總計,查詢花費0.0004秒)。

group | name 
--------+-------- 
Berries | blueberry, raspberry, strawberry 
Citrus | grapefruit, lime 
Pear | NULL 

PHP結果:

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

每個人都歡迎任何有更好的改善更好地實施?

2
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']; 
} 
+1

默認SEPARATOR是','沒有空格,您想要將其更改爲GROUP_CONCAT(b.name SEPARATOR',') –

+0

感謝@ExplosionPills發現我'GROUP_CONCAT'!你的代碼段不起作用,沒有這樣一個PHP函數'fetch',爲什麼我需要'array'。我只是通過工作示例添加了我的答案。 @PugganSe,感謝發佈關於'SEPARATOR'! – Binyamin

+1

'fetch'是速記..你應該用一點創造力來推斷你需要的答案。 –