2014-03-31 26 views
0

我有一個名爲goods的表,看起來像這樣。從mysql表中獲取多個關聯的行

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

我試圖讓從該表中,關聯數組,其中數組的索引應該是成爲nametype和值。最終的結果應該看起來像這樣。

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

我試圖SELECT name FROM goods AS type WHERE type IN ('car', 'bike', 'motor bike') 但仍然給出了數組的索引結果type

+0

在這種情況下的'type'是一列標題。儘管可以更改列標題標籤,但據我所知,不可能具有動態列標題標籤。您可以在php代碼中實現這種外部SQL。 – Kami

+0

你的SQL查詢很好,你可以發佈你的PHP? – mituw16

+0

@Kami我的確在PHP中使用foreach循環,但是我在跳過,可能有辦法在mysql中這樣做。 – iOi

回答

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") 
    ); 
+0

到目前爲止,這是最好的方法。唯一的缺點是我必須使用'explode()'來獲取汽車名稱。可能沒有任何名稱中包含逗號的汽車/自行車 – iOi

+0

@iOi您可以將分隔符更改爲不是逗號**,​​但取決於您將如何使用MySQL查詢的結果,可能有更好的閱讀方式所以除非你可以提供更多關於如何使用結果的信息,我猜這是最接近你想要的。** – Prix

+0

@iOi我也在底部添加了一種不同的方式,你可能會喜歡,因爲你不會有爆炸的結果。 – Prix

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 

(OR)直接的方式爲每個評論

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

+0

難道你不能直接做到嗎? 'CASE WHEN type ='car'THEN name END AS car,'? – Prix

+0

是的,我們可以。我以另一種方式去了。據說,解決問題的方法不止一種。 – Rahul

+0

這種方法很好,但不方便。它需要將名稱明確寫入語句中。 – iOi

相關問題