从多个表中获取数据,消除重复值

时间:2013-11-22 13:10:21

标签: php mysql

我想从mysql数据库中的两个表中获取数据。表1包含名称等,表2包含详细信息(我无法更改此给定结构)。

表1

id   | name   |
7    | Test0  |
8    | Test1  | 

表2

name_id   | a_id   | value
8         | 1      | detail 1
8         | 2      | detail 2

表1中给定名称的每个细节都存储在表2中的一行中。我可以像这样获取数据:

$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM 
 table1 
LEFT JOIN table2 ON table2.name_id=table1.id ';

mysql_select_db('database');
$result = mysql_query( $sql, $conn );
if(! $result )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_object($result)){
echo 
"Id: ".$row->id.", Name: ".$row->name.", Attribute: ".$row->value."<br />";
}
mysql_close($conn);

输出结果为:

Id: 7, Name: Test0, Attribute:
Id: 8, Name: Test1, Attribute: value 1
Id: 8, Name: Test1, Attribute: value 2

但我宁愿需要这样的东西

Id: 7, Name: Test0, Attribute: 
Id: 8, Name: Test1, Attribute: value 1, value 2, value 3...

所有细节应显示在一行中,并带有相应的名称。

任何帮助将不胜感激!

解决方案:

SELECT table1.id, table1.name, GROUP_CONCAT(table2.value) as value 
FROM table1 
LEFT JOIN table2 ON table2.name_id=table1.id
GROUP BY table1.id, table1.name

非常感谢!

2 个答案:

答案 0 :(得分:1)

尝试GROUP_CONCAT,如下所示:

SELECT table1.id, table1.name, GROUP_CONCAT(table2.value) as value 
FROM table1 
LEFT JOIN table2 ON table2.name_id=table1.id
GROUP BY table1.id, table1.name

答案 1 :(得分:-1)

我们可以使用以下查询来实现它,

SELECT table1.id, table1.name, GROUP_CONCAT(table2.value) as attribute 
FROM table1
LEFT JOIN table2 ON table2.name_id = table1.id
GROUP BY table1.id, table1.name

指向group_contact用法的链接:http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-group_concat.php