从mysql表中获取多个关联的行

时间:2014-03-31 13:28:13

标签: php mysql sql

我有一个名为goods的表,看起来像这样。

id |  name   |   type       |    
1  |  honda  |   car        |  
2  |  bianci |   bike       |  
3  |  ferari |   car        |  
4  |  hurley |   motor bike |  
4  |  bar    |   motor bike | 

我试图从这个表中获取一个关联数组,其中数组的索引应该是type,值应该是name。最终结果应该是这样的。

array("car"=>"honda", "bike"=>"bianci", "car"=>"ferrari", "motor bike"=>"hurley");

我试过SELECT name FROM goods AS type WHERE type IN ('car', 'bike', 'motor bike') 但仍然为数组提供索引type的结果。

2 个答案:

答案 0 :(得分:1)

您的查询应如下所示:

  SELECT GROUP_CONCAT(`name`) AS `brand`,
         `type` 
    FROM goods
   WHERE `type` IN ('car', 'bike', 'motor bike')
GROUP BY `type`

上述查询的结果如下:

name            |   type
-------------------------------
honda, ferari   |   car
bianci          |   bike
hurley, bar     |   motor bike

在你的PHP上会是这样的:

$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $result[$row['type']] = $row['brand'];
}
print_r($result);

由于您无法在阵列上重复使用键,因此使用GROUP BY对类型进行分组,并使用GROUP_CONCAT将名称分组为单个字符串,我们可以得到接近于你想要的:

array("car" => "honda, ferrari",
      "bike" => "bianci",
      "motor bike" => "hurley, bar"
     );

另一种方法是:

  SELECT `name`,
         `type` 
    FROM goods
   WHERE `type` IN ('car', 'bike', 'motor bike')

在你的PHP上会是这样的:

$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    $result[$row['type']][] = $row['name'];
}
print_r($result);

使用此方法,您可以将类型作为键,使用数组作为值,并使用foreach或任何其他循环轻松读取所有名称:

array("car" => array("honda", "ferrari"),
      "bike" => array("bianci"),
      "motor bike" => array("hurley", "bar")
     );

答案 1 :(得分:1)

根据您的询问是否要通过SQL实现,那么您可以做的就是可以有更好的方法。因此,在您的PHP代码中,您将以某种方式处理那些空值/空值。不知道PHP。

select 
isnull(car,'') as car,
isnull(bike,'') as bike,
isnull([motor bike],'') as 'motor_bike' 
from
(
SELECT 
case when name in ('honda','ferari') then name end as car, 
case when name = 'bianci' then name end as bike,
case when name in ('bar','hurley') then name end as 'motor bike'
FROM goods 
) tab

(或)根据评论的直接方式

SELECT 
case when type = 'car' then name end as car, 
case when type = 'bike' then name end as bike,
case when type = 'motor bike' then name end as 'motor bike'
FROM goods 

这将导致

enter image description here