【问题标题】:mySQL reusing calculated value in WHERE clausemySQL 在 WHERE 子句中重用计算值
【发布时间】:2017-07-27 13:27:14
【问题描述】:
SELECT 
  table1.a,
  table1.b, 
  (SELECT b 
  FROM table2 
  WHERE table2.b - table1.a < 10 
  LIMIT 0,1) as test
FROM table1 
WHERE table1.b < test;

我正在尝试在查询的 WHERE 部分中使用 SELECT "variable" test 中收到的结果。

知道如何做到这一点而不必重新计算或在 WHERE 中再次进行任何操作吗?到目前为止,这就是我设法使它工作的方式。

【问题讨论】:

  • 不可能,不能在 WHERE 子句中使用别名。但是在 WHERE 子句中重复完全相同的计算通常不是问题,这在内部得到了优化,因此计算只发生一次。

标签: mysql select where


【解决方案1】:

你不能在 WHERE 中使用它,但你可以使用 HAVING。你有你的结果。但这不是很高效。

SELECT table1.a, table1.b,
  (select b FROM table2 WHERE table2.b-table1.a<10 LIMIT 0,1) as test 
FROM table1
HAVING table1.b<test

如果你想使用 WHERE,那么你也必须在这个位置创建你的 SUBSELECT

SELECT table1.a, table1.b,
  (select b FROM table2 WHERE table2.b-table1.a<10 LIMIT 0,1) as test 
FROM table1
WHERE table1.b < (select b FROM table2 WHERE table2.b-table1.a<10 LIMIT 0,1)

【讨论】:

  • 我不能这样做SELECT table1.a, table1.b, @test:=(select b FROM table2 WHERE table2.b-table1.a&lt;10 LIMIT 0,1) as test FROM table1 WHERE table1.b &lt;@test
【解决方案2】:

我想,这个查询会给出你想要的结果。

SELECT table1.a ,
 table1.b ,
 table2.b 
FROM table1 ,
 table2 
WHERE 
table1.b < table2.b AND
 (table2.b - table1.a) < 10

【讨论】:

    【解决方案3】:

    您的test 变量等于table2.b,其值小于table1.a +10。因此可以将查询转换为

    SELECT 
      table1.a,
      table1.b, 
      table2.b AS test
    FROM table1 
    JOIN table2 
    ON (table2.b - table1.a < 10) AND (table1.b < table2.b)
    GROUP BY table1.a, table1.b;
    

    这里使用GROUP BY子句来防止table1.atable1.b 组合并获得每个 table1.atable1.b 组合的第一个 table2.b 值。

    【讨论】:

      猜你喜欢
      • 2016-11-18
      • 2014-10-12
      • 1970-01-01
      • 2015-02-14
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多