我有一张名为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。
发布于 2014-03-31 14:03:42
您的查询应该如下所示:
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")
);发布于 2014-03-31 14:06:35
根据您的要求,如果您想通过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 这将导致

https://stackoverflow.com/questions/22762826
复制相似问题