mysql - 简单的 SELECT 过程

标签 mysql sql

我在MySQL中有这个程序

DROP PROCEDURE IF EXISTS `AddNotificationOnPosts`;

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `AddNotificationOnPosts`(from_user INT(11),on_post_id INT(11),in_group_id INT(11))
BEGIN
    DECLARE num_rows INT DEFAULT 0;

    SELECT count(notification_id) FROM notifications_posts 
    WHERE from_user = 1;

END $$
DELIMITER ;

和这张表

notification_id from_user   on_post_id  in_group_id date
2   1   162 3   2012-07-11 12:01:08
3   19  163 1   2012-07-11 12:03:26
4   19  164 1   2012-08-10 17:42:36
5   1   165 3   2012-08-29 12:14:01
6   1   165 3   2012-08-29 12:14:29

当我执行时:

SET @p0 =  '1';
SET @p1 =  '2';
SET @p2 =  '3';
CALL `AddNotificationOnPosts` ( @p0 , @p1 , @p2 );

它给了我:

count(notification_id)
5
为什么?因为它们只是user_id 1的3条记录

我该如何执行此过程:

  1. 未设置值时给出错误或警告

  2. 从过程中获取变量,例如

    SELECT count(notification_id) FROM notifications_posts 
    WHERE from_user = @from_user;
    

最佳答案

您应该为参数使用不同的名称:

CREATE PROCEDURE AddNotificationOnPosts
(arg_from_user INT(11),arg_on_post_id INT(11),arg_in_group_id INT(11))
BEGIN
    DECLARE num_rows INT DEFAULT 0;

    IF(arg_from_user  IS NULL OR arg_from_user = '')
    THEN 
        SELECT "Error:Invalid argument for userID" AS error_code;
    ELSE
        SELECT count(notification_id) 
        INTO num_rows
        FROM notifications_posts 
        WHERE from_user = arg_from_user;
    END IF;

    SELECT num_rows;
END $$

关于mysql - 简单的 SELECT 过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12176442/

相关文章:

php - jqgrid 从一个网格更新两个表

mysql - WordPress 数据库错误 The table is full for query UPDATE

几天之间的mysql查询并计算日期之间的天数

mysql - 使用 EXIST 命令创建 sql View 语句

sql - 如何查看记录是否更新?

php - 从 mysql 数据库中检索为 blob 图像时图像损坏

c# - 单击组合框时如何避免乘法

mysql - 使用大量与 wp_postmeta(键/值表)的内部联接来改进查询

Python - pandas ==> WINDOW 聚合

Mysql查询为每次迭代按顺序对记录进行排序?