MySQL存储过程SELECT,三个WHERE CLAUSE值和ORDER BY

时间:2014-05-06 22:06:47

标签: mysql sql stored-functions

我的存储函数似乎无法正常工作我返回1​​0行NULL和40个警告。

我想写一个存储函数,它在开始日期D1和结束日期D2之间返回customer_id X的最高付费。

该表的结构如下:

sales(customer_id CHAR(1), date DATE, paid INT)

示例行:

sales(A, 2014-12-20, 3456)

我的存储功能:

DELIMITER $$
    CREATE FUNCTION highest_monthly_paid(x CHAR(1), D1 DATE, D2 DATE) 
      RETURNS INT
      DETERMINISTIC
    BEGIN
        DECLARE highest_fee INT;

        SELECT paid INTO highest_fee
        FROM sales
        WHERE customer_id = x 
        AND date > D1
        AND date < D2
        ORDER BY paid DESC LIMIT 1;
        RETURN highest_fee;
    END
    $$

这不起作用还是我最好使用某种子查询?如果两种方法都有用,我应该使用哪种方法?

我尝试过MAX(paid)而不是LIMIT

我调用函数的查询:

SELECT highest_monthly_paid(A,  2013-12-10,  2013-12-25)
FROM sales;

数据库中有两行,其customer_id为A:

+-------------+-------+----------+------------+--------+
| customer_id | model | quantity | day        | paid   |
+-------------+-------+----------+------------+--------+
| A           | 2002  |        2 | 2013-12-19 |   1898 |
| A           | 3002  |        1 | 2013-12-18 |    239 |
+-------------+-------+----------+------------+--------+

我的结果:

mysql> SELECT highest_monthly_paid(A,  2013-12-10,  2013-12-25)
    -> FROM sales;
+------------------------------------------------------------+
| highest_monthly_paid(A,  2013-12-10,  2013-12-25) |
+------------------------------------------------------------+
|                                                       NULL |
|                                                       NULL |
|                                                       NULL |
|                                                       NULL |
|                                                       NULL |
|                                                       NULL |
|                                                       NULL |
|                                                       NULL |
|                                                       NULL |
|                                                       NULL |
+------------------------------------------------------------+
10 rows in set, 30 warnings (0.00 sec)

1 个答案:

答案 0 :(得分:0)

我认为以下查询应该足以为给定日期范围内的每个客户获取highest_fee。如果您有其他要求,请告诉我们。

SELECT customer_id, MAX(paid) AS highest_fees
FROM sales
WHERE date BETWEEN '2013-12-10' AND '2013-12-25'
GROUP BY customer_id