开发者

MySQL returning value from a SELECT statement

I keep getting this error: Result consisted of more than one row

I have this function:

DROP FUNCTION IF开发者_如何学Go EXISTS db.GetUserIDByCourseID;
CREATE FUNCTION db.`GetUserIDByCourseID`(CourseID int) RETURNS int(11)
BEGIN
      SELECT (c.user_id + COALESCE(pi.user_id, 0) + COALESCE(p.user_id, 0))
        INTO @user_id
        FROM courses c
             LEFT JOIN users u
                ON u.user_id = c.user_id
             LEFT JOIN partners p
                ON p.partner_id = c.partner_id
             LEFT JOIN partners_individual pi
                ON pi.individual_id = c.individual_id;
             WHERE c.course_id = CourseID;

      SELECT user_type_id
        INTO @user_type_id
        FROM users
       WHERE user_id = @user_id;

      RETURN @user_type_id;
   END;


When SELECTing into a variable, the result set must consist of exactly one row. In your current example, it seems likely that the first select statement will return more than one row; you can check that by executing it by hand for the values of CourseID that are giving trouble. What to do about it I couldn't say, as that depends on the details of your design.


You could try SELECT TOP 1. Either or both your SELECT statements could be returning multiple rows. I think you need to sit down and 1: understand your data model and 2: understand your data.

To see what's going on more clearly, run these queries by themselves and look at the result sets:

SELECT (c.user_id + COALESCE(pi.user_id, 0) + COALESCE(p.user_id, 0))
  FROM courses c
  LEFT JOIN users u
      ON u.user_id = c.user_id
LEFT JOIN partners p
  ON p.partner_id = c.partner_id
LEFT JOIN partners_individual pi
  ON pi.individual_id = c.individual_id;
    WHERE c.course_id = CourseID;

SELECT user_type_id
  FROM users
  WHERE user_id = @user_id;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜