Reputation: 200
I have a sample database:
brand(id, name)
(1, 'Apple')
(2, 'Dell')
model(id, name, brand_id)
(1, 'Macbook', 1)
(2, 'Iphone', 1)
(3, 'Vostro', 2)
And php mysql code:
<?php
// Make a MySQL Connection
$query = "SELECT * FROM model";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$brand_id = array();
$brand_id = array_unique($row['brand_id']);
?>
<table>
<?php for($i=0; $i<count(brand_id); $i++) {?>
<tr>
<td><?php echo $row['name'] ?></td>
<tr/>
<?php }?>
</table>
And result return 2 tr of 2 brand_id, but it show result all model name
<table>
<tr><td>Macbook, Iphone, Vostro</td></tr>
<tr><td>Macbook, Iphone, Vostro</td></tr>
</table>
How to fix it to result is:
<table>
<tr><td>Macbook, Iphone</td></tr>
<tr><td>Vostro</td></tr>
</table>
Upvotes: 0
Views: 69
Reputation: 263893
You need to use an aggregate function, GROUP_CONCAT
, for that:
SELECT GROUP_CONCAT(b.`name`)
FROM brand a
INNER JOIN model b
on a.id = b.brand_id
GROUP BY a.`Name`
Upvotes: 4