【问题标题】:Using Distinct in SQL query在 SQL 查询中使用 Distinct
【发布时间】:2013-10-01 04:21:16
【问题描述】:

请找到下面给出的查询:

SELECT DISTINCT 
        reco_index_content_code,
        reco_index_content_name,
        reco_index_content_url
    FROM tbl_reco_index_contents
    WHERE
        reco_index_user_action_at_select = 1
        AND user_profile_number = 1

我需要选择 reco_index_content_name 来区分。

应该如何修改上述查询,以实现这一点,使得没有重复的reco_index_content_name 行?

【问题讨论】:

  • 您将如何处理以下reco_index_content_code?例如,只选择最低的代码?
  • 如果有重复,你想返回哪一行。请注意,“不关心”通常表示设计不佳。
  • @Strawberry -- 我明白,但我这样做是为了临时修复演示。可以是任意行。
  • 那么它可以是任何值吗?对其他列使用常量:SELECT DISTINCT '' AS reco_index_content_code, reco_index_content_name, '' AS reco_index_content_url FROM ...

标签: mysql sqlite


【解决方案1】:

标准解决方案已记录并使用不相关的子查询,如下所示:

SELECT x.* 
  FROM my_table x
  JOIN 
     ( SELECT grouping_id
            , MIN(ordering_id) min_ordering_id 
         FROM my_table 
        GROUP 
           BY grouping_id  
     ) y
    ON y.grouping_id = x.grouping_id
   AND y.min_ordering_id = x.ordering_id; 

【讨论】:

  • 您能告诉我如何将其应用于我上面的查询吗?抱歉,我在这里没有太多专业知识。
  • 也许不是,但我想你可以弄清楚 ;-)
  • 好的.. my_table = tbl_reco_index_contents ,grouping_id=reco_index_content_code。 ordering_id 是什么?
  • 根据你的描述,grouping_id是reco_index_content_name
猜你喜欢
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 2012-08-09
相关资源
最近更新 更多