SQL JOIN获取库存项目和备用项目的列表

时间:2013-10-20 19:23:45

标签: sql join foreign-keys sybase

我有一个代表零售商品的数据库。有些项目有多个扫描码,但实质上是相同的项目,即。他们的名字,成本和零售总是一样的。要对此进行建模,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

3 个答案:

答案 0 :(得分:1)

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

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

据我了解查询,您需要从库存表中获取所有内容。然后,您需要同时使用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