【问题标题】:Select statement for Oracle SQLOracle SQL 的选择语句
【发布时间】:2016-05-02 07:56:23
【问题描述】:

我有一张桌子说,

column1 column2
a   apple
a   ball
a   boy
b   apple
b   eagle
b   orange
c   bat
c   ball
c   cork

现在我想根据不包含“apple”的行获取 column1,如果任何行中有“apple”,也忽略 column1 中的值。所以在上表中只有“C”必须返回。 我是 Oracle SQL 的新手,我知道 Select column1 from table where column2 != 'apple' 不起作用。我需要一些帮助。

【问题讨论】:

  • 那么在这种情况下你只需要选择column1的值只需要选择C吗?
  • 是的。没错..@StanislovasKalašnikovas
  • 您尝试过什么,遇到了什么问题?
  • NOT EXISTS 是一个好的开始。

标签: sql oracle select


【解决方案1】:

您可以在下面使用DISTINCTNOT IN

QUERY 1 使用 NOT IN

select distinct col1
from t
where col1 not in (select col1 from t where col2 = 'Apple')

QUERY 2 使用 NOT EXISTS

根据@jarlh 评论,您可以在以下内容中使用NOT EXISTS

select distinct col1
from #t t1
where not exists (select 1 from #t t2 where col2 = 'Apple' and t1.col1 = t2.col1)

样本数据

create table t
(
    col1 nvarchar(60),
    col2 nvarchar(60)
)
insert into t values
('a','apple')
,('a','ball')
,('a','boy')
,('b','apple')
,('b','eagle')
,('b','orange')
,('c','bat')
,('c','ball')
,('c','cork')

【讨论】:

  • 我从不推荐NOT IN,因为许多人觉得太令人惊讶的空行为。 NOT EXISTS 是“空安全”
  • @jarlh 用你的建议更新了我的答案以使用NOT EXISTS
【解决方案2】:

假设 column1NOT NULL 你可以使用:

SELECT DISTINCT t.column1
FROM table_name t
WHERE t.column1 NOT IN (SELECT column1
                        FROM table_name
                        WHERE column2 = 'apple');

LiveDemo

要获取所有列和行,请将DISTINCT t.column1 更改为*

【讨论】:

    【解决方案3】:
    Select * from tbl
    Left join (
        Select column1 from tbl
        Where column2 like '%apple%'
        Group by column1
        ) g on tbl.colum1 = g.column1
    Where g.column1 is null
    

    在我看来,您需要找到所有对苹果有任何引用的 colum1 值的摘要。然后列出与汇总列表不匹配的行(g)

    【讨论】:

      【解决方案4】:

      如果我理解得很好,您需要 column1 的值,这样在您的表中不存在 column1column2 中的 'apple' 值相同的行;你可以用 SQL 翻译这个:

      Select column1
      from your_table t
      where not exists ( 
                         select 1
                         from your_table t2
                         where t2.column1 = t1.column1
                           and t2.column2= 'apple'
                       )
      

      这只是获得结果的可能方法之一,因此您可以通过多种方式重写它;我相信这种写法与逻辑足够相似,可以清楚地解释如何用纯 SQL 编写逻辑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-28
        • 2018-06-27
        • 2021-02-05
        • 2021-02-19
        • 1970-01-01
        • 2011-06-09
        相关资源
        最近更新 更多