mysql查询选择案例多于1个表

时间:2013-08-21 08:12:43

标签: mysql

我遇到选择案例的问题..

表格

  
      
  1. 模板(temp_id,temp_title,temp_applyto,temp_status,start_date,end_date)

         
        

    [其中temp_apply存储int 1-individu,2-branch,3-dept和4-position]

      
  2.   
  3. individu (applyto_id,applyto_individu,applyto_temp)

  4.   
  5. 分支(applyto_id,applyto_branch,applyto_temp)

  6.   
  7. dept (applyto_id,applyto_dept,applyto_temp)

  8.   
  9. 职位(applyto_id,applyto_position,applyto_temp)

  10.   
  11. 员工(身份证,姓名,分支机构,部门,职位)

  12.   

递减:

我想检查用户他是否在个人,分支,部门或职位。如果 temp_applyto(表格模板)= 1 ,那么我想检查表 individu 如果用户存在,如果 temp_applyto = 2 那么我想要检查表分支,如果用户存在且同样继续。

到目前为止的查询:

SELECT (CASE WHEN temp_applyto=1 
    THEN (SELECT applyto_temp FROM individu 
          WHERE applyto_individu=$user)
    WHEN temp_applyto=2 
    THEN (SELECT a.applyto_temp FROM branch a, staff b 
          WHERE >a.applyto_branch=b.branch AND b.id=$user) 
    WHEN temp_applyto=3 
    THEN (SELECT a.applyto_temp FROM dept a, staff b 
          WHERE >a.applyto_dept=b.dept AND b.id=$user) 
    WHEN temp_applyto=4 THEN (SELECT a.applyto_temp FROM position a, staff b 
          WHERE a.applyto_position=b.position AND b.id=$user) 
    ELSE 0 end) as template_temp 
FROM template 
WHERE '2013-08-21' BETWEEN start_date AND end_date

我收到此错误:子查询返回超过1行

2 个答案:

答案 0 :(得分:0)

错误很明显,因为我们的一个子查询返回了多行。您可以在每个子查询上使用LIMIT 1。但是,如果您想获得多行,可以使用UNION这样的

SELECT template_temp FROM
(
    (SELECT applyto_temp AS template_temp, 1 AS temp_applyto FROM individu WHERE applyto_individu = $user) UNION
    (SELECT a.applyto_temp AS template_temp, 2 AS temp_applyto FROM branch a, staff b WHERE a.applyto_branch=b.branch AND b.id=$user) UNION
    (SELECT a.applyto_temp AS template_temp, 3 AS temp_applyto FROM dept a, staff b WHERE a.applyto_dept=b.dept AND b.id=$user) UNION
    (SELECT a.applyto_temp AS template_temp, 4 AS temp_applyto FROM `position` a, staff b WHERE a.applyto_position=b.`position` AND b.id=$user)
) AS combine INNER JOIN template
ON (combine.temp_applyto = template.temp_applyto)
WHERE '2013-08-21' BETWEEN start_date AND end_date

答案 1 :(得分:0)

错误是不言自明的:您的一个子查询返回多行。有几种方法可以解决您的问题。一个简单的方法是将LIMIT 1添加到每个子选择中。或者,您可以选择行数 - 然后将结果与0进行比较:

SELECT (CASE WHEN temp_applyto=1 
    THEN (SELECT COUNT(*) FROM individu 
          WHERE applyto_individu=$user)
    WHEN temp_applyto=2 
    THEN (SELECT COUNT(*) FROM branch a, staff b 
          WHERE >a.applyto_branch=b.branch AND b.id=$user)
    WHEN temp_applyto=3 
    THEN (SELECT COUNT(*) FROM dept a, staff b 
          WHERE >a.applyto_dept=b.dept AND b.id=$user) 
    WHEN temp_applyto=4
    THEN (SELECT COUNT(*) FROM position a, staff b 
          WHERE a.applyto_position=b.position AND b.id=$user)
    ELSE 0 END) as template_temp 
FROM template
WHERE '2013-08-21' BETWEEN start_date AND end_date

这将返回一个数字 - 如果没有匹配则为0,如果没有则匹配数量。