SQL use column from subselect in where clause(SQL在where子句中使用子选择中的列)
问题描述
我有一个类似这样的查询:
I have a query that looks something like that:
SELECT a, b, c,
(SELECT d from B limit 0,1) as d
FROM A
WHERE d >= 10
当我在没有 where 子句的情况下运行查询时,我得到了我想要的结果,但是当我添加 where 子句时,查询失败.
I get the result that I want when I run the query without the whereclause but when I add the where clause the query fails.
有没有人建议如何解决这个问题?
Does anyone have a suggestion how to solve that?
推荐答案
不能在 WHERE 子句中使用列别名.
You can't use a column alias in WHERE clause.
因此,您可以将查询包装在外部选择中并在那里应用您的条件
So you either wrap your query in an outer select and apply your condition there
SELECT *
FROM
(
SELECT a, b, c,
(SELECT d FROM B LIMIT 0,1) d
FROM A
) q
WHERE d >= 10
或者您可以在 HAVING 子句中引入该条件
or you can introduce that condition in HAVING clause instead
SELECT a, b, c,
(SELECT d FROM B LIMIT 0,1) d
FROM A
HAVING d >= 10
另一种方法是使用 CROSS JOIN 并在 WHERE 子句中应用您的条件
Yet another approach is to use CROSS JOIN and apply your condition in WHERE clause
SELECT a, b, c, d
FROM A CROSS JOIN
(
SELECT d FROM B LIMIT 0,1
) q
WHERE d >= 10
这里是所有上述查询的 SQLFiddle 演示.
Here is SQLFiddle demo for all above mentioned queries.
这篇关于SQL在where子句中使用子选择中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL在where子句中使用子选择中的列
基础教程推荐
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在多列上分布任意行 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- oracle区分大小写的原因? 2021-01-01
