简体   繁体   English

如何简化多重转换MySql select语句?

[英]How to simplify a multiple cast MySql select statement?

I am trying to perform a MySql select with many conditions, but want to perform a string comparison on a column that is an integer datatype. 我正在尝试在许多条件下执行MySql select,但是想对作为整数数据类型的列执行字符串比较。 Is there a way to do this without having to cast the column to a varchar on every single condition within the where clause? 有没有一种方法可以不必在where子句中的每个条件下都将列强制转换为varchar?

SELECT COUNT(*) 
FROM tablename 
WHERE CAST(col1 AS VARCHAR(10)) NOT LIKE '558%' 
  AND CAST(col1 AS VARCHAR(10)) NOT LIKE '566%' 
  AND CAST(col1 AS VARCHAR(10)) NOT LIKE '567%'
  AND CAST(col1 AS VARCHAR(10)) NOT LIKE '568%'
  AND CAST(col1 AS VARCHAR(10)) NOT LIKE '569%'
  AND CAST(col1 AS VARCHAR(10)) NOT LIKE '579%';

Before you ask why I'm not doing integer comparison: Instead of casting to a varchar, I could also just use plain integer comparison, but then I still would have to perform a math operation, ie col1/100000, for every item in the where clause, which leads to the same problem as to how can I simplify the statement? 在您问我为什么不进行整数比较之前:除了强制转换为varchar外,我还可以使用普通整数比较,但是我仍然必须对算术运算中的每个项目执行数学运算,即col1 / 100000。 where子句,导致与如何简化语句相同的问题?

You can use subquery: 您可以使用子查询:

SELECT COUNT(*)
FROM
( 
  SELECT CAST(col1 AS VARCHAR(10)) AS col1
  FROM tablename
) AS t
WHERE t.col1 NOT LIKE '558%'
...

The direct answer to your question is that casts are implicit in MySQL, so col1 NOT LIKE '556%' is equivalent to what you're doing. 您问题的直接答案是强制转换在MySQL中是隐式的,因此col1 NOT LIKE '556%'等同于您所做的事情。

It's always best to avoid using functions that reference column names in the WHERE clause, because that disables the use of indexes and requires every row in the table to be evaluated. 始终最好避免使用在WHERE子句中引用列名的函数,因为这会禁用索引的使用,并要求对表中的每一行进行求值。 I assume that you are aware of that, since you mentioned you would still "have to do a math operation." 我假设您已经意识到这一点,因为您提到您仍然“必须进行数学运算”。

If you actually know the scale of the number then a more correct query would be... 如果您实际上知道数字的小数位数,则可以进行更正确的查询。

WHERE (col1 < 556 * 100000 OR col1 > 556 * 100000)
  AND ...

If that's logically correct based on what you are doing, then it's a better solution, because the optimizer will do that math only once, converting those into constants, rather than doing it once per row. 如果根据您的工作在逻辑上是正确的,那么这是一个更好的解决方案,因为优化器只会执行一次该数学运算,然后将其转换为常量,而不是每行执行一次。

Also note that if you do know the scale of the numbers, then LIKE '556______' is also more logically valid than using % since _ matches exactly one character, where % matches zero or more. 还要注意,如果您确实知道数字的小数位数,则LIKE '556______'在逻辑上比使用%更有效,因为_恰好匹配一个字符,其中%匹配零个或多个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM