0

我正在使用一个 mysql 存储过程来检查一个 ID 是否存在于 5-6 个表中。如果这些表中的任何一个包含该 ID,我将一个标志设置为 true。最后,我使用 SELECT 选择标志。

SP的参数如下:

->settings_type =“分支”
->settings_id(被搜索的id)

如果搜索到的 ID 出现在这 6 个表中的任何一个中,我如何知道从哪个表中找到了 ID?

BEGIN
DECLARE boolStatus BOOL DEFAULT FALSE;

IF settings_type = "branch"
THEN
    IF ((SELECT COUNT(tblbatches.intBranchId)   FROM tblbatches         WHERE tblbatches.intBranchId        = settings_id > 0) OR 
         (SELECT COUNT(tblexams.intBranchId)        FROM tblexams           WHERE tblexams.intBranchId      = settings_id > 0) OR
         (SELECT COUNT(tblquestions.intBranchId)    FROM tblquestions   WHERE tblquestions.intBranchId  = settings_id > 0) OR
         (SELECT COUNT(tblresults.intBranchId)  FROM tblresults     WHERE tblresults.intBranchId        = settings_id > 0) OR
         (SELECT COUNT(tblstudents.intBranchId) FROM tblstudents        WHERE tblstudents.intBranchId   = settings_id > 0) OR
         (SELECT COUNT(tblsubjects.intBranchId) FROM tblsubjects        WHERE tblsubjects.intBranchId   = settings_id > 0)
        )
        THEN
            SET boolStatus := TRUE;
    END IF;
    SELECT boolStatus;
END IF;
END
4

1 回答 1

0

重写程序的一种方法

DELIMITER $$
CREATE PROCEDURE sp_name(IN settings_type VARCHAR(32), IN settings_id INT)
BEGIN
  IF settings_type = 'branch' THEN
    SELECT COALESCE(SUM(total), 0) > 0 status, 
           GROUP_CONCAT(source) source
      FROM
    (
      SELECT 'tblbatches' source, COUNT(*) total
        FROM tblbatches
       WHERE intBranchId = settings_id
       UNION ALL
      SELECT 'tblexams', COUNT(*)
        FROM tblexams 
       WHERE intBranchId = settings_id
       UNION ALL
      SELECT 'tblquestions', COUNT(*) 
        FROM tblquestions 
       WHERE intBranchId = settings_id
       UNION ALL
      SELECT 'tblresults', COUNT(*)
        FROM tblresults
       WHERE intBranchId = settings_id
       UNION ALL
      SELECT 'tblstudents', COUNT(*)
        FROM tblstudents
       WHERE intBranchId = settings_id
       UNION ALL
      SELECT 'tblsubjects', COUNT(*)
        FROM tblsubjects
       WHERE intBranchId = settings_id
    ) q 
     WHERE total > 0;
  END IF;
END$$
DELIMITER ;

找到匹配记录时的示例输出:

| 状态 | 来源 |
----------------------------------
| 1 | tbl批次,tbl结果 |

当他们没有

| 状态 | 来源 |
------------------
| 0 | (空) |

这是SQLFiddle演示

于 2013-08-11T08:37:13.260 回答