简体   繁体   English

将select的聚合结果分配给mySQL中的用户变量

[英]Assigning an aggregate result from select to a user variable in mySQL

I am trying to save a user variable with a result of count function from a table. 我正在尝试从表中保存具有count函数结果的用户变量。

Executing this query: 执行此查询:

SELECT @var:=count(distinct(column1)) FROM table_name;

Returns: 返回值:

@var:=count(distinct(column1))
41243

Then executing: 然后执行:

SELECT @var;

Returns: 返回值:

@var
Blob

When I expected 41243. 当我预期为41243。

When I assign a value to a user variable it works as expected. 当我给用户变量赋值时,它可以按预期工作。

What am I doing wrong? 我究竟做错了什么?

Thanks. 谢谢。


Edit: I corrected $var to @var. 编辑:我将$ var改正为@var。

I am issuing the query from mySQL Workbench for testing. 我正在从mySQL Workbench发出查询以进行测试。 I will use it eventually from PHP. 我最终将在PHP中使用它。

Another related question: Can I assign a SELECT result to a user variable without having the result (In my example: 41243) sent back to the client (as it will slow the query if I'm using it from PHP). 另一个相关的问题:是否可以将SELECT结果分配给用户变量,而没有将结果(在我的示例中为41243)发送回客户端(如果从PHP使用它会减慢查询速度)。

You simply have to convert the blob type return value: 您只需要转换Blob类型的返回值即可:

SELECT @var:=count(distinct(column1)) FROM table1;
SELECT convert(@var,unsigned);

Because the result is blob (binary string), you simply have to convert it to integer (in this case unsigned int, but if you use 'signed', then you will get signed integer. 因为结果是blob(二进制字符串),所以您只需要将其转换为整数(在这种情况下为unsigned int),但是如果使用“ signed”,则将获得带符号的整数。

Hope this helps. 希望这可以帮助。

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

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