0

我有一个代表零售商品的数据库。有些项目有多个扫描码,但本质上是同一个项目,即。他们的名字、成本和零售总是一样的。为了对此建模,数据库具有以下结构

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小提琴

4

3 回答 3

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小提琴

于 2013-10-20T19:29:00.647 回答
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当您知道行不会在两组结果之间重复时是更快的选择(因此数据库不需要检查重复项)。

于 2013-10-20T19:29:09.457 回答
0

据我了解查询,您需要从库存表中获取所有内容。然后,您需要同时使用inventory_table和选择所有备选方案alternates_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
于 2013-10-20T19:30:18.540 回答