简体   繁体   中英

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 )) . 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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