【问题标题】:sql query to return data based on combination conditionssql查询根据组合条件返回数据
【发布时间】:2017-09-26 06:31:53
【问题描述】:

需要编写一个sql来根据组合条件过滤表中的记录。如果 column_1 是“A”,然后 column_2 是“100”,或者如果 column_1 是“B”,然后 column_2 是“200”,则显示记录

    select * 
    from tableTmp
    where 
name="student"
and ((column_1="A" and column_2 = "100") OR (column_1="B" and column_2 = "200"))

当第一个条件不存在时,它会显示我们想要的。但是如果有第一个条件,那么 column_1="C" 数据仍然会显示,查询被打破。

你知道为什么吗?

【问题讨论】:

  • 你能显示示例数据吗?
  • "column_1='C' data still will show" 是什么意思?这意味着“查询已损坏”?您需要更加清楚,首先显示一些示例数据和示例输出,并向我们解释输出中不需要的部分是什么。
  • "student" 是列引用,而不是(标准)SQL 中的字符串常量。该查询是无效的标准 SQL(除非您有一个名为 "student" 的列)。您使用的是哪个 DBMS?

标签: sql


【解决方案1】:

对文字使用单引号:

select * 
from tableTmp
where name='student'
and (
    (column_1='A' and column_2 = '100') 
 OR (column_1='B' and column_2 = '200')
 )

但是我看不到该查询如何返回 column_1 值“C”。

铌。如果 column_2 是数值数据类型,请勿使用单引号。

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多