Using a variable in MySQL Select Statment in a Where Clause

心已入冬 提交于 2019-12-11 10:10:12

问题


I would like to know if it's possible to find a value in a select statement and use it in a where clause like:

SELECT col1, MAX(col2) - COUNT(DISTINCT col3) as variable
FROM table
WHERE col1 > variable

"table" is pretty big, and I want to narrow down the records the query has to look at as quickly as possible.

I know this isn't bit of code isn't possible as written (#1054 - Unknown column 'variable' in 'where clause'), but is there anyway to figure out the value of "variable" and then use it in the WHERE clause?


回答1:


You could try subquery syntax, also called nested select.

I think something like:

SELECT col1 WHERE col1 > (SELECT MAX(col2) - COUNT(DISTINCT col3)) 

See the MySQL manual for some better examples.




回答2:


In some cases you can replicate an expression in a WHERE clause, as demonstrated by RedFilter. In other cases, this isn't possible and you can use a HAVING clause, e.g.

SELECT col1, MAX(col2) - COUNT(DISTINCT col3) as variable
FROM table
HAVING col1 > variable

HAVING is less efficient, think of it as a resultset post-processor rather than something the query optimizer can do anything with.



来源:https://stackoverflow.com/questions/3567863/using-a-variable-in-mysql-select-statment-in-a-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!