mySQL 在 WHERE 子句中重用计算值

mySQL reusing calculated value in WHERE clause

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 中使用它,但你可以在 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 ,
 table2.b 
FROM table1 ,
 table2 
WHERE 
table1.b < table2.b AND
 (table2.b - table1.a) < 10

您的 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.aand table1.b 组合,并为每个 table1.atable1.b 组合获取第一个 table2.b 值。