-1

我有 2 张桌子。Table1包含商店 #1 Table2中的产品库存并包含商店 #2 中的产品库存

Table1:
upc  | description   | QtyOnHand1
4050 | cantaloupe    | 10
4131 | fuji apples   | 20
5033 | strawberries  | 5

Table2
upc  | description | QtyOnHand2
4050 | cantaloupe  | 15
4131 | fuji apples | 23
4121 | aprictos    | 13

我应该使用什么选择语句来获得以下结果。

upc  | description  | QtyOnHand1 | QtyOnHand2
4050 | cantaloupe   | 10         | 15
4131 | fuji apples  | 20         | 23
5033 | strawberries | 5          | null
4121 |  apricots    | null       | 13
4

2 回答 2

6

问题是你需要一个FULL OUTER JOINMySQL 不支持的。FULL OUTER JOIN 将返回两个表中的行,这将允许您返回两个数据中都不存在的行,这些行将是 forstrawberriesapricots

您可以使用类似于以下的 UNION 查询来模拟 FULL OUTER JOIN:

SELECT t1.upc,
  t1.description,
  t1.QtyOnHand1,
  t2.QtyOnHand2
FROM table1 t1
LEFT JOIN table2 t2 
  ON t1.upc= t2.upc
UNION
SELECT t2.upc,
  t2.description,
  t1.QtyOnHand1,
  t2.QtyOnHand2
FROM table1 t1
RIGHT JOIN table2 t2 
  ON t1.upc = t2.upc;

请参阅SQL Fiddle with Demo

可以这样写的另一种方法是upc从两个表中获取每个表的 DISTINCT 列表,然后对表使用 LEFT JOIN:

select d.upc,
  coalesce(t1.description, t2.description) description,
  t1.QtyOnHand1,
  t2.QtyOnHand2
from
(
  select upc from table1
  union 
  select upc from table2
) d
left join table1 t1
  on d.upc = t1.upc
left join table2 t2
  on d.upc = t2.upc;

请参阅SQL Fiddle with Demo

作为旁注,您可能需要重新考虑为每个表创建单独的表,store当您拥有 100 家商店等时,这将是一场维护噩梦。

于 2013-09-09T19:16:13.380 回答
-4

您将使用如下所示的 Join 语句:

select table1.upc, table1.description, table1.QtyOnHand1, table2.QtyOnHand2 
from Table1, table2 
left join table2 on table1.upc = table2.upc;
于 2013-09-09T19:09:38.703 回答