简体   繁体   English

MySql - 在 select 查询中使用变量,而 where 条件又提供了一行

[英]MySql - Using variables in select query and where condition gives one more additional row

I am using variables in select query to calculate a value and based on the value I have added where condition in query.我在 select 查询中使用变量来计算一个值,并根据我在查询中添加 where 条件的值。

What my problem in it gives addtional one more row whatever field value is.无论字段值是什么,我的问题都会再增加一行。

For example if the field value is 1 on all rows in that table then it gives 20 plus additional one more row 21.例如,如果该表中所有行的字段值为 1,那么它会给出 20 加上另外一行 21。

Kindly help in solving this issue.请帮助解决这个问题。

How to add condtion based on value calculated as I can't use SUM, it will aggregate and returns only one value.如何根据计算的值添加条件,因为我不能使用 SUM,它将聚合并仅返回一个值。

Below is sample query I use.下面是我使用的示例查询。

SET @var = 0;
SELECT  @var := @var + field FROM table1 WHERE  @var <= 20

MySql version 5.5.45 MySql 版本 5.5.45

Check for检查

SELECT t1.(fieldset)
FROM source_table t1
JOIN source_table t2 ON t1.ordering_field <= t2.ordering field
GROUP BY t1.(fieldset)
HAVING SUM(t2.amount_field) <= @needed_sum
ORDER BY SUM(t2.amount_field) DESC [LIMIT 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM