【问题标题】:Select using ifnull and subquery error SQL Error [1242] [21000]: Subquery returns more than 1 rowSelect using ifnull and subquery error SQL Error [1242] [21000]: Subquery returns more than 1 row
【发布时间】:2021-03-31 02:52:16
【问题描述】:

我想从某个子查询中获取数据,但它只返回 SQL 错误 [1242] [21000]:子查询返回超过 1 行,我的代码有问题吗?

  SELECT
    u.id user_id, p.id user_profileid, p.firstname, p.lastname,
    IFNULL((SELECT SUM(ROUND((DATEDIFF(end_date, start_date) / 365))) FROM employee_experience WHERE user_profileid = p.id GROUP BY user_profileid),0) AS experience,
    (SELECT jobtitle FROM employee_experience WHERE end_date IN (SELECT MAX(end_date) FROM employee_experience GROUP BY user_profileid) AND user_profileid = p.id) AS last_jobtitle,
    IFNULL((SELECT lastsalary FROM employee_experience WHERE end_date IN (SELECT MAX(end_date) FROM employee_experience GROUP BY user_profileid) AND user_profileid = p.id),0) AS last_salary
  FROM
    users u
    LEFT JOIN employee_profile p ON (u.id = p.user_id)
    LEFT JOIN employee_experience e ON (p.id = e.user_profileid)
  WHERE
     (u.roleid = '2') and (u.isverified = '1')
  GROUP BY
    u.id, p.id

【问题讨论】:

    标签: mysql subquery


    【解决方案1】:

    ifnull 仅适用于 1 个值,您的子查询可以返回多个值, 要解决此问题,您可以在子查询中使用 limit 1

        SELECT 
               u.id user_id, p.id user_profileid, p.firstname, p.lastname, IFNULL((SELECT
     SUM(ROUND((DATEDIFF(end_date, start_date) / 365))) FROM
     employee_experience WHERE
     user_profileid = p.id GROUP BY
     user_profileid limit 1),0) AS experience,
     (SELECT jobtitle FROM
     employee_experience WHERE end_date
     IN (SELECT MAX(end_date) FROM
     employee_experience GROUP BY
     user_profileid) AND user_profileid =
     p.id) AS last_jobtitle, IFNULL((SELECT
     lastsalary FROM employee_experience
     WHERE end_date IN (SELECT
     MAX(end_date) FROM employee_experience GROUP BY
     user_profileid) AND user_profileid = p.id
     limit 1),0) AS last_salary FROM users u
     LEFT JOIN employee_profile p ON (u.id =
     p.user_id) LEFT JOIN employee_experience e ON (p.id =
     e.user_profileid) 
    WHERE 
         (u.roleid = '2')
     and (u.isverified = '1') 
    GROUP BY u.id, p.id
    
    

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2012-03-15
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多