我有一个类似
的查询WITH a AS ( SELECT *
FROM inventory_tagalongs
WHERE TagAlong_ItemNum <> 'bokiwi2'
)
SELECT inventory.itemnum
, inventory.itemname
, inventory.ItemType,inventory.dept_id
FROM inventory
LEFT OUTER JOIN a
ON inventory.itemnum = a.itemnum
JOIN departments
ON inventory.dept_id = departments.dept_id
JOIN categories
ON departments.subtype = categories.cat_id AND categories.description = 'vapors'
我试图从较低的a
中排除syntax
的结果,但是无论left outer join.....
是否存在,返回的结果都完全相同。
我的语法不正确吗?
答案 0 :(得分:1)
下午好。请尝试以下方法:
select
inventory.itemnum
, inventory.itemname
, inventory.ItemType
, inventory.dept_id
from inventory
join departments on inventory.dept_id=departments.dept_id
join categories on departments.subtype=categories.cat_id and categories.description='vapors'
WHERE NOT EXISTS(
select 1 from inventory_tagalongs B where inventory.itemnum = b.itemnum
AND B.TagAlong_ItemNum <>'bokiwi2');
CTE对此问题有所思考。这样可以通过易于阅读的代码实现目标,并且性能也应更好。
谢谢约翰。
答案 1 :(得分:1)
如果您试图获得没有标签的结果,则逻辑将被反转。您想要:
SELECT i.itemnum, i.itemname, i.ItemType, i.dept_id
FROM inventory i JOIN
departments d
ON i.dept_id = d.dept_id JOIN
categories c
ON d.subtype = c.cat_id AND
c.description = 'vapors' LEFT OUTER JOIN
a
ON i.itemnum = a.itemnum
WHERE a.itemnum IS NULL;
您根本不需要CTE。通常写为:
WITH a AS (
)
SELECT i.itemnum, i.itemname, i.ItemType, i.dept_id
FROM inventory i JOIN
departments d
ON i.dept_id = d.dept_id JOIN
categories c
ON d.subtype = c.cat_id AND
c.description = 'vapors' LEFT OUTER JOIN
inventory_tagalongs it
ON i.itemnum = it.itemnum AND it.TagAlong_ItemNum = 'bokiwi2'
WHERE a.itemnum IS NULL;
而且-如另一个答案所述-NOT EXISTS
是解决此问题的另一种典型方法。