简体   繁体   English

显示特定字段的所有结果,并通过内部联接显示其余结果

[英]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. 如果我尝试使用elseif作为该代码的日期,则会显示错误。 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? 您尝试了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 http://dev.mysql.com/doc/refman/5.0/zh/group-by-functions.html#function_group-concat

use GROUP_CONCAT , 使用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. 列名称更改为您在表上找到的原始名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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