Mysql - 我可以获取子选择结果并在 WHERE 子句中使用它吗?

发布于 2024-07-23 08:03:10 字数 411 浏览 7 评论 0原文

我想在 where 子句中获取并使用从 MySQL 中的子选择返回的值。 这可能吗? 似乎没有必要将子查询写出两次——但是如果我需要的话,MySQL 是否足够聪明,只运行一次?

我尝试了以下方法,但不起作用:

SELECT 
  (SELECT 1 FROM table WHERE somereallycomplicatedclause = 'something')
      AS subselectresult 
FROM content WHERE subselectresult = 1

这会产生此错误:

#1054 - Unknown column 'subselectresult' in 'where clause'  

谢谢

I want to both fetch and use in a where clause the value returned from a sub-select in MySQL. Is this possible? It seems unecessary to write the sub-query out twice - however if I need to, will MySQL be clever enough to only run it one?

I have tried the following which does not work:

SELECT 
  (SELECT 1 FROM table WHERE somereallycomplicatedclause = 'something')
      AS subselectresult 
FROM content WHERE subselectresult = 1

This generates this error:

#1054 - Unknown column 'subselectresult' in 'where clause'  

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回梦 2024-07-30 08:03:10

不能在 WHERE 子句中使用列别名。 尝试将其放入 HAVING 中,然后它应该可以工作。

这里的解释: http://dev.mysql.com /doc/refman/5.0/en/problems-with-alias.html

you can't use column aliases in a WHERE clause. try putting it in HAVING and it should work then.

Explanation here: http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

千柳 2024-07-30 08:03:10

您显示的查询很奇怪。 您可以通过这种方式获得相同的结果(交叉产品):

SELECT S.One
FROM contacts,
(SELECT DISTINCT 1 as One FROM table WHERE somereallycomplicatedclause = 'something') S

我认为您应该更多地说明您尝试解决的问题(例如,子查询和联系人表之间的链接是什么)?

Your query as you displayed is strange. You can achieve the same result this way (cross product):

SELECT S.One
FROM contacts,
(SELECT DISTINCT 1 as One FROM table WHERE somereallycomplicatedclause = 'something') S

I think you should say more about what do you try to solve (e.g. what is the link between the sub query and the contacts table)?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文