例如,假设有 3 个表:
物理项目
ID
SELLER_ID
NAME
COST
DIMENSIONS
WEIGHT
数字项目
ID
SELLER_ID
NAME
COST
DOWNLOAD_PATH
卖方
ID
NAME
项目 ID 保证在两个项目表中都是唯一的。我想使用类型标签按顺序选择给定卖家的所有商品 ID。我想出了:
查询 A
SELECT PI.ID AS ID, 'PHYSICAL' AS TYPE
FROM PHYSICAL_ITEM PI
JOIN SELLER S ON PI.SELLER_ID = S.ID
WHERE S.NAME = 'name'
UNION
SELECT DI.ID AS ID, 'DIGITAL' AS TYPE
FROM DIGITAL_ITEM DI
JOIN SELLER S ON DI.SELLER_ID = S.ID
WHERE S.NAME = 'name'
ORDER BY ID
查询 B
SELECT ITEM.ID, ITEM.TYPE
FROM (SELECT ID, SELLER_ID, 'PHYSICAL' AS TYPE
FROM PHYSICAL_ITEM
UNION
SELECT ID, SELLER_ID, 'DIGITAL' AS TYPE
FROM DIGITAL_ITEM) AS ITEM
JOIN SELLER ON ITEM.SELLER_ID = SELLER.ID
WHERE SELLER.NAME = 'name'
ORDER BY ITEM.ID
查询 A 似乎是最有效的,但它看起来也不必要地重复(2 个表连接到同一个表,2 个 where 子句在同一个表列上)。查询 B 在某种程度上对我来说看起来更干净(没有重复),但它看起来效率也低得多,因为它有一个子查询。可以这么说,有没有办法两全其美?