英文:
Not Exists in Oracle
问题
SELECT SUP_STATUS FROM SUPPLIER
SUP_STATUS
A
SELECT sup_status FROM supplier WHERE NOT EXISTS(SELECT
sup_status FROM supplier WHERE sup_status='I')
Desired Output
SUP_STATUS
A
MAIN QUERY WHERE NOT EXISTS(SELECT sup_status FROM supplier
WHERE sup_status='I')
英文:
I have the table(supplier) column(sup_status) contains the value 'A' and 'I' and now i am selecting the value 'A' using not exists. But in real scenario the main query returns the sup_stauts 'A' and 'I' so I need to select the sup_status='A' records using not exists. But result is not coming. I do not want to use not in operator.
For Example
SELECT SUP_STATUS FROM SUPPLIER
SUP_STATUS
A
I
select sup_status from supplier where not exists(select
sup_status from supplier where sup_status='I')
Desired Output
SUP_STATUS
A
MAIN QUERY where not exists(select sup_status from supplier
where sup_status='I')
答案1
得分: 2
当您使用以下查询时:
select sup_status
from supplier
where not exists(
select sup_status
from supplier
where sup_status='I'
)
那么子查询与外部查询不相关,因此子查询会搜索表的整个结果集,看是否存在供应商状态为 I
的行。如果整个结果集中存在一行,则查询将不会输出任何内容。
如果您想将子查询与外部查询关联起来,那么您需要在查询中指定这一点。例如,如果您想在supplier_name
上进行关联:
select sup_status
from supplier s
where not exists(
select sup_status
from supplier x
where x.sup_status='I'
and s.supplier_name = x.supplier_name
)
您还可以使用分析函数,以便不必使用相关子查询:
SELECT sup_status
FROM (
SELECT sup_status,
COUNT(CASE sup_status WHEN 'I' THEN 1 END)
OVER (PARTITION BY supplier_name) AS has_i
FROM supplier
)
WHERE has_i = 0;
英文:
When you use the query:
select sup_status
from supplier
where not exists(
select sup_status
from supplier
where sup_status='I'
)
Then the sub-query is not correlated to the outer query and so the sub-query is searching the table's entire result set to see if there is any row where the supplier status is I
. If there exists one row within the entire result set then the query will output nothing.
If you want to correlate the sub-query to the outer query then you need to specify that in the query. For example, if you want to correlate on supplier_name
:
select sup_status
from supplier s
where not exists(
select sup_status
from supplier x
where x.sup_status='I'
and s.supplier_name = x.supplier_name
)
You could also use analytic functions so that you do not have to use a correlated sub-query:
SELECT sup_status
FROM (
SELECT sup_status,
COUNT(CASE sup_status WHEN 'I' THEN 1 END)
OVER (PARTITION BY supplier_name) AS has_i
FROM supplier
)
WHERE has_i = 0;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论