简体   繁体   English

如何将参数传递给函数?

[英]How can I pass a parameter to a function?

Here is my table structure: 这是我的表结构:

-- users
+----+--------+
| id |  name  |
+----+--------+
| 1  | Jack   |
| 2  | Peter  |
| 3  | Martin |
+----+--------+

-- reputations
+----+-------+---------+
| id |  repo | user_id |
+----+-------+---------+
| 1  | 5     | 2       |
| 2  | 10    | 1       |
| 3  | -2    | 3       |
| 3  | 5     | 2       |
+----+-------+---------+

Also I have a function like this: 我也有这样的功能:

DROP FUNCTION IF EXISTS user_repo //
CREATE FUNCTION user_repo(user_id INT) RETURNS INT
BEGIN
    DECLARE repo INT;
    SELECT SUM(repo) INTO repo FROM reputations WHERE user_id = user_id;
    RETURN repo;
END;//

It works correctly when I call it like SELECT user_repo(2) (it returns 10 , ( 5 + 5 )) . 当我像SELECT user_repo(2)一样调用它时,它可以正常工作(它返回10 ,( 5 + 5 )) Now I need to use that function in another query. 现在,我需要在另一个查询中使用该功能。 All I want to achieve is a list of users with their reputations. 我要实现的只是拥有其声誉的用户列表。 So this is the expected result: 所以这是预期的结果:

+----+--------+------+
| id |  name  | repo |
+----+--------+------+
| 1  | Jack   | 10   |
| 2  | Peter  | 10   |
| 3  | Martin | -2   |
+----+--------+------+

How can I get that? 我该怎么办? I mean how can I use that defined function into this? 我的意思是如何在其中使用定义的函数?

SELECT u.*, /* that function */ FROM users WHERE 1;

试试看

SELECT u.*, user_repo(u.id) as repo FROM users u WHERE 1;

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

相关问题 如何在存储过程中使用单引号传递输入参数 - how can i pass input parameter with single quote in Stored Procedure 如何将mysql数据作为ajax参数传递 - How can I pass mysql data as ajax parameter 如何通过查询将参数传递给存储过程? - How can I pass parameter to stored procedure through a query? 我可以在SOUNDEX()函数中传递多个参数以获得多值结果吗 - can i pass more than one parameter within SOUNDEX() function to get multiple value result 如何将参数传递给LIMIT? 我可以将所有查询输出保存在一个字符串中吗? - How can i pass parameter to LIMIT ? Can i save all query output in one string? 如何在Codeigniter中将多个参数传递给函数或查询 - How to pass multiple parameter to a function or query in codeigniter 我可以将变量传递给函数吗? - Can I pass a variable into a function? 我如何使用将根据用户而变化的参数查询函数中的计数? - how can i query count in function with parameter that will change according to user? 如何将字符串传递给AWS Redshift用户定义函数? - How can I pass a string to AWS redshift user defined function? 如何将结果从 javascript 传递给 laravel 函数作为数量? - How can I pass RESULT from javascript to laravel function as amount?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM