【问题标题】:foreign key select only one record from table外键从表中只选择一条记录
【发布时间】:2014-08-12 14:46:34
【问题描述】:

我使用的是 sql server 2012。我有两个表,M_SALES 和 M_SALES_COUNTRY。 M_SALES 包含一个名为 sale_id 的主键。 M_SALES_COUNTRY 还包含一个名为 sale_id 的字段,它是它的外键。 M_SALES_COUNTRY 还包含一个名为 country_code 的字段,该字段可以为空。

所以 M_SALES 包含一个唯一的 sale_id。 M_SALES_COUNTRY 可以包含多个相同的 sale_id。

对于来自 M_SALES_COUNTRY 的 1 条记录(可能有多个,但我只想要一个)的查询,为 M_SALES 表中的每个 sales_id 返回,这很好,也是我想要的。但是我想知道是否可以添加更多条件。

如果 M_SALES 中的 sale_id 引用 M_SALES_COUNTRY 中的多个 sale_id,我希望它返回 country_code 字段不为空的记录。如果所有记录 country_code 为 null,则返回 null。请看下面两个简单的例子。

 sale_id     country_code   
 AAA5555     null
 AAA5555     null
 AAA5555     D56

我要返回的记录是 D56。

下一个例子

 sale_id     country_code   
 AAA5555     null
 AAA5555     null
 AAA5555     null

只要返回一条记录,任何记录都可以在这里使用。

查询

 select M_SALES.*, M_SALES_COUNTRY.*
 from M_SALES cross apply
 (
    select top 1 M_SALES_COUNTRY.*
    from M_SALES_COUNTRY
    where M_SALES.sale_id = M_SALES_COUNTRY.sale_id     
  ) MA_DEALS_COUNTRY
  order by M_SALES.sale_id

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您可以使用子查询消除重复项并加入该表,即

    SELECT *
    FROM M_SALES 
    JOIN (SELECT sales_id, max(country_code) as country_code
                        FROM M_SALES_COUNTRY GROUP BY sales_id
        ) M_SALES_COUNTRY
    ON M_SALES_COUNTRY.sales_id = M_SALES.sales_id
    

    我还会考虑清理 M_Sales_Country 表以使 sales_id 是唯一的,或者创建另一个版本,其中包含销售 id 的唯一值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 2020-11-02
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多