MYSQL JOIN SELECT语句 - 省略重复项

时间:2010-05-07 14:44:30

标签: mysql select join union

我想加入以下两个查询,但我有重复......有可能删除duplacted for this:

(
SELECT bar_id, bar_name, town_name, bar_telephone, 
        (subscription_type_id *2) AS subscription_type_id
FROM bar, sportactivitybar, towns, subscriptiontype
WHERE sport_activity_id_fk =14
    AND bar_id = bar_id_fk
    AND town_id = town_id_fk
    AND subscription_type_id = subscription_type_id_fk
)
UNION 
(
SELECT bar_id, bar_name, town_name, bar_telephone, 
         subscription_type_id
FROM bar, towns, subscriptiontype
WHERE town_id = town_id_fk
    AND subscription_type_id = subscription_type_id_fk
)
ORDER BY subscription_type_id DESC , RAND( )

请注意,我需要省略那些具有较低subscription_type_id

的重复项

3 个答案:

答案 0 :(得分:2)

如果我理解正确的话,一个简单的GROUP BY,只扣留最大订阅类型就可以了。

SELECT  dupAlias.bar_id
        , dupAlias.bar_name
        , dupAlias.town_name
        , dupAlias.bar_telephone
        , MAX(dupAlias.subscription_type_id) AS subscription_type_id
FROM    (
          SELECT  bar_id
                  , bar_name
                  , town_name
                  , bar_telephone
                  , (subscription_type_id *2) AS subscription_type_id
          FROM    bar
                  , sportactivitybar
                  , towns
                  , subscriptiontype
          WHERE   sport_activity_id_fk =14
                  AND bar_id = bar_id_fk
                  AND town_id = town_id_fk
                  AND subscription_type_id = subscription_type_id_fk
          UNION 
          SELECT  bar_id
                  , bar_name
                  , town_name
                  , bar_telephone
                  , subscription_type_id
          FROM    bar
                  , towns
                  , subscriptiontype
          WHERE   town_id = town_id_fk
                  AND subscription_type_id = subscription_type_id_fk
        ) dupAlias
GROUP BY
        dupAlias.bar_id, dupAlias.bar_name, dupAlias.town_name, dupAlias.bar_telephone
ORDER BY 
        dupAlias.subscription_type_id DESC , RAND( )

答案 1 :(得分:1)

您可以将查询括起来:

SELECT bar_id, bar_name, town_name, bar_telephone, 
    max(subscription_type_id)
FROM
(
    (
    SELECT bar_id, bar_name, town_name, bar_telephone, 
            (subscription_type_id *2) AS subscription_type_id
    FROM bar, sportactivitybar, towns, subscriptiontype
    WHERE sport_activity_id_fk =14
        AND bar_id = bar_id_fk
        AND town_id = town_id_fk
        AND subscription_type_id = subscription_type_id_fk
    )
    UNION 
    (
    SELECT bar_id, bar_name, town_name, bar_telephone, 
             subscription_type_id
    FROM bar, towns, subscriptiontype
    WHERE town_id = town_id_fk
        AND subscription_type_id = subscription_type_id_fk
    )
) x
GROUP BY bar_id, bar_name, town_name, bar_telephone
ORDER BY subscription_type_id DESC , RAND( )

答案 2 :(得分:0)

最快的方法是使用临时表。从那里你可以将第一个查询插入到临时表中,然后只通过使用临时表的外连接或者通过使用not来从第二个查询中插入那些不在临时表中的行在声明中。或者您可以插入所有第二个查询,只需在临时表中选择使用group by子句。