2009-08-10 92 views
0

對不起,可怕的標題,不知道如何解釋這一點。我有一個查詢,看起來像這樣:需要幫助我的查詢

SELECT `name`, `latitude`, `longitude`, `indoor`, `address`, 
    `phone`, `email`, `website`, `closed` 
FROM rocks INNER JOIN 
    (SELECT DISTINCT id FROM rock_types WHERE type="DWS" or type="Top rope") 
    AS types ON rocks.id=types.id 
WHERE (latitude>-180 AND latitude<180) AND (longitude>-180 AND longitude<180) 

除了什麼我得到現在,我想獲得的與每個ID相關聯的類型列表。我怎樣才能做到這一點?由於

+0

那麼你的標題應該是這樣的,「獲得的與SQL每個ID相關聯的列表類型」 – random 2009-08-10 04:04:37

回答

1

下面是使用傳統的連接語法我的看法:

SELECT rocks.name, 
     rocks.latitude, 
     rocks.longitude, 
     rocks.indoor, 
     rocks.address, 
     rocks.phone, 
     rocks.email, 
     rocks.website, 
     rocks.closed, 
     rock_types.type 

FROM rocks, 
     rock_types 

WHERE rocks.latitude > -180     AND 
     rocks.latitude < 180     AND 
     rocks.longitude > -180     AND 
     rocks.longitude < 180     AND 
     rocks.type_id = rocks_types.id  AND 
     rock_types.type IN ('DWS', 'Top rope') 

rocks.id = rocks_types.id做兩個表之間的聯繫。

這裏是你如何編寫使用INNER JOIN相同的查詢(既導致了同樣的結果)

SELECT rocks.name, 
     rocks.latitude, 
     rocks.longitude, 
     rocks.indoor, 
     rocks.address, 
     rocks.phone, 
     rocks.email, 
     rocks.website, 
     rocks.closed, 
     rock_types.type 

FROM rocks 
     INNER JOIN rocks_types ON rocks.type_id = rocks_types.id 

WHERE rocks.latitude > -180     AND 
     rocks.latitude < 180     AND 
     rocks.longitude > -180     AND 
     rocks.longitude < 180     AND 
     rock_types.type IN ('DWS', 'Top rope') 

編輯:基於您的評論,下面會給你一個逗號分隔的類型列表:

SELECT rocks.name, 
     rocks.latitude, 
     rocks.longitude, 
     rocks.indoor, 
     rocks.address, 
     rocks.phone, 
     rocks.email, 
     rocks.website, 
     rocks.closed, 
     (SELECT GROUP_CONCAT(DISTINCT rock_types.type SEPARATOR ',') 
     FROM  rock_types 
     WHERE  rock_types.id = rocks.id    AND 
        rock_types.type IN ('DWS', 'Top rope') 
     GROUP BY rock_types.id 
     ) AS type 

FROM rocks 

WHERE rocks.latitude > -180 AND 
     rocks.latitude < 180  AND 
     rocks.longitude > -180 AND 
     rocks.longitude < 180 
+0

比你安德魯。如果每個搖滾只有一種類型與此相關,那麼這將起作用。但是,情況並非總是如此。岩石表是由id索引的岩石列表。 rock_types表將該id映射到1個或更多類型,例如,id = 1可能在rock_types中有2行,DWS爲1,頂部爲1。這個查詢將只返回其中的一個。是否有可能獲得與該ID相關的所有類型? – giroy 2009-08-10 04:43:23

+0

啊,應該包括在你原來的問題中。在這種情況下,讓我解決這個問題。 – 2009-08-10 05:18:32

+0

我編輯我的問題與解決你的問題。 – 2009-08-10 05:28:05

0
SELECT `name`, `latitude`, `longitude`, `indoor`, `address`, 
    `phone`, `email`, `website`, `closed`, 
    (SELECT GROUP_CONCAT(type SEPARATOR ',') FROM rock_types 
     WHERE (type="DWS" or type="Top rope") and rock_types.id=rocks.id group by id) types 
FROM rocks 
WHERE (latitude>-180 AND latitude<180) AND (longitude>-180 AND longitude<180)