Sql中的括号

时间:2018-07-03 13:47:28

标签: sql sql-server

我的表格中有一个列Product_Category,其中包含类似

的值
'Fit', 'Tight', 'Wide', 'Tall','Short', 'Thin'

我还有一个名为Product_number的列,其值:

'1234','1235','1236','1237','1238','1324','1325'

在查询中,我有一个where子句,我想确保括号正确。这是下面的where子句:

where (Product_Category= 'Fit'
       and Product_number IN ('1234','1235','1236','1237','1238'))
   or (Product_Category in ('Tight', 'Wide') and Product_number= '1324')
   or (Product_Category in ('Tall', 'Short', 'Thin') and Product_number = '1325')

我的括号(括号)顺序正确吗?

编辑:添加了单引号。

2 个答案:

答案 0 :(得分:1)

尝试一下:

where (Product_Category = 'Fit' and  Product_number IN (1234, 1235, 1236, 1237, 1238)) or
      (Product_Category in ('Tight', 'Wide') and Product_number = 1324) or
      (Product_Category in ('Tall', 'Short', 'Thin') and Product_number = 1325)

如果代码对齐,您可以看到括号是否更容易平衡。

重要的是,我假设product_number是一个数字。将其与数字进行比较。类型转换会对性能产生不利影响。

答案 1 :(得分:0)

不太

select 0 
    where (Product_Category= 'Fit' and Product_number IN ('1234',1235','1236','1237','1238')) or (Product_Category in ('Tight', 'Wide') and Product_number= '1324') or (Product_Category in ('Tall', 'Short', 'Thin') and Product_number= '1325')

给予

 Unclosed quotation mark after the character string ')

'。

如此

select 0 
where (Product_Category= 'Fit' and Product_number IN ('1234','1235','1236','1237','1238')) or (Product_Category in ('Tight', 'Wide') and Product_number= '1324') or (Product_Category in ('Tall', 'Short', 'Thin') and Product_number= '1325')

就可以了

注意

    '1234',1235'

位于vaLID中,可能是'1234','1235',但是通过键入'1234',1235'来逃避胭脂报价,您可能会有'1234',1235'-这就是SQL所做的不知道你是不是故意

-您不需要所有的寄生虫-并且优先于OR且IN是单个TRUE / FALSE运算-尽管额外的寄生虫并没有真正的害处

where Product_Category= 'Fit' and Product_number IN ('1234','1235','1236','1237','1238')
     or Product_Category in ('Tight', 'Wide') and Product_number= '1324'
     or Product_Category in ('Tall', 'Short', 'Thin') and Product_number =   '1325'