简体   繁体   中英

display all results for certain field and one for rest with inner join

I need to display shops in created area with date for making order. I created a third table to join two that are here already (shops & area) and joined that with inner join. First, I got results like this:

area name: name1
shops: shop1
date: date1

area name: name1
shops: shop2
date: date1

and I need:

area name: name1
shops: shop1, shop2
date: date1

then I found some code and included it in script, but it works only for one row (name in code below). If I try with elseif for date with that code it displays wrong. Code is below.

<?php
include('db.php'); 
$result = mysql_query("SELECT * FROM area INNER JOIN area_join ON area.id = area_join.area_id INNER JOIN shops ON area_join.shops_id = shops.id ") or die("Error: " . mysql_error());; 
while($data = mysql_fetch_assoc($result)){
if($data['name'] != $groupname){
echo "<br><hr>Area name: ".$data['name']."<br />Shops: ";
$groupname = $data['name'];
}
echo "".$data['shop_name'].", ";
}
?>

Did you try group_concat? (cant test it now, but i think is this way)

SELECT areaname,group_concat(shops) FROM area INNER JOIN area_join ON area.id =    area_join.area_id INNER JOIN shops ON area_join.shops_id = shops.id
Group by areaname

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

use GROUP_CONCAT ,

SELECT  areaName,
        GROUP_CONCAT(DISTINCT shopname) shopList
FROM    area 
        INNER JOIN area_join 
            ON area.id = area_join.area_id 
        INNER JOIN shops 
            ON area_join.shops_id = shops.id 
GROUP   BY  areaName

change the column names to your original names on found on the tables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM