2008-11-07 138 views
3

在我的應用程序中,有發佈者和類別。一個發佈者可以屬於幾個類別。當我創建我的mysql事務時,它將爲它所屬的每個類別返回相同的發佈者記錄。這裏的查詢:從mysql查詢獲取不同記錄

SELECT 
    grdirect_publisher.name, 
    grdirect_publisher.short_description, 
    grdirect_publisher.thumb_image, 
    grdirect_publisher.url, 
    grdirect_category.name AS catname 
FROM 
    grdirect_publisher 
JOIN 
    grdirect_publisher_categories 
    ON 
    grdirect_publisher.id = grdirect_publisher_categories.publisher_id 
JOIN 
    grdirect_category 
    ON 
    grdirect_publisher_categories.category_id = grdirect_category.id

回報:

從本質上講,富應該只在結果中顯示一次。

+0

如果你想Foo只出現一次,你想看哪個名字:視頻遊戲或音樂? – 2008-11-08 08:31:08

回答

4

您可以使用DISTINCT,但如果結果集中的任何列有不同的值,則會強制該行被複制。如果您想將清單縮小至一排每name,那麼你必須使用DISTINCT,你必須省略catname柱:

SELECT DISTINCT 
    grdirect_publisher.name, 
    grdirect_publisher.short_description, 
    grdirect_publisher.thumb_image, 
    grdirect_publisher.url 
FROM 
. . . 

另一種解決方案,而不是使用DISTINCT是MySQL的聚合函數GROUP_CONCAT()它允許你取多個值的組中,併產生一個逗號分隔的列表:

SELECT 
    grdirect_publisher.name, 
    grdirect_publisher.short_description, 
    grdirect_publisher.thumb_image, 
    grdirect_publisher.url, 
    GROUP_CONCAT(grdirect_category.name) AS catname 
. . . 
GROUP BY grdirect_publisher.id; 

所以,你必須決定如何你想結果集只看得到正確的解決方案。