【问题标题】:SQL JOIN to get a list of intventory items and alternate itemsSQL JOIN 获取库存项目和备用项目的列表
【发布时间】:2013-10-20 19:23:45
【问题描述】:

我有一个代表零售商品的数据库。有些项目有多个扫描码,但本质上是同一个项目,即。他们的名字、成本和零售总是一样的。要对此进行建模,the database has the following structure:

Inventory_Table

INV_PK | INV_ScanCode | INV_Name | INV_Cost | INV_Retail
  1    | 000123456789 |  Muffins | 0.15     | 0.30    
  2    | 000987654321 |  Cookie  | 0.25     | 0.50    
  3    | 000123454321 |  Cake    | 0.45     | 0.90    


Alternates_Table

ALT_PK | INV_FK | ALT_ScanCode
  1    |   2    | 000999888777
  2    |   2    | 000666555444
  3    |   2    | 000333222111

现在说我想要一个数据库中所有扫描码的列表,我将如何加入表以获得以下输出:

ScanCode     | Name    | Cost | Retail
000123456789 | Muffins | 0.15 | 0.30
000987654321 | Cookie  | 0.25 | 0.50 
000999888777 | Cookie  | 0.25 | 0.50
000666555444 | Cookie  | 0.25 | 0.50
000333222111 | Cookie  | 0.25 | 0.50
000123454321 | Cake    | 0.45 | 0.90 

SQL Fiddle

【问题讨论】:

    标签: sql join foreign-keys sybase


    【解决方案1】:

    您正在寻找union

    SELECT it.INV_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail 
    FROM   Inventory_Table AS it
    UNION ALL
    SELECT at.ALT_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail 
    FROM   Inventory_Table AS it
      INNER JOIN Alternate_Table AS at
      ON at.INV_FK = INV_PK
    

    UNION ALL 是当您知道行不会在两组结果之间重复时更快的选择(因此数据库不需要检查重复项)。

    【讨论】:

      【解决方案2】:
      SELECT it.INV_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail 
      FROM   Inventory_Table AS it
      
      union all
      
      SELECT at.ALT_ScanCode, it.INV_Name, it.INV_Cost, it.INV_Retail 
      FROM   Alternate_Table AS at
      inner join Inventory_Table AS it on at.INV_FK = it.INV_PK
      

      SQL Fiddle

      【讨论】:

        【解决方案3】:

        据我了解,您需要从库存表中获取所有内容。然后,您需要同时使用inventory_tablealternates_table 选择所有替代项。这建议使用union all 进行整体查询:

        select scancode, name, cost, retail
        from inventory_table i
        union all
        select a.scancode, i.name, i.cost, i.retail
        from inventory_table i join
             alternates_table a
             on a.inv_fk = i.inv_pk
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-09-22
          相关资源
          最近更新 更多