从mysql查询中获取不同的记录

时间:2008-11-07 22:54:18

标签: mysql join distinct

在我的应用程序中,有发布者和类别。一个发布者可以属于多个类别。当我创建我的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

返回:

name    short_description   thumb_image url catname
------------------------------------------------------------
Foo Lorem Ipsum...      images/pic.png  d.com   Video Games
Foo Lorem Ipsum...      images/pic.png  d.com   Music
Bar Blah Blah...        images/tic.png  e.com   Music

基本上,Foo只应在结果中显示一次。

1 个答案:

答案 0 :(得分: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;

因此,您必须决定如何使用结果集来获得正确的解决方案。