MySQL将变量值添加到存储过程中的结果集中而不是子查询

时间:2019-04-17 10:42:57

标签: mysql sql stored-procedures

这是子查询,可以很好地处理所需的结果,现在我正在为相同的结果编写存储过程。

我想在存储过程逻辑中用作

  • 声明变量
  • 设置它们
  • 用于查询

查询:

SELECT payloadstr,
       starttime
FROM   pa
WHERE  conid IN (SELECT conid
                 FROM   con
                 WHERE  lognid IN (SELECT id
                                   FROM   log
                                   WHERE  phyid IN (SELECT id
                                                    FROM   phyid
                                                    WHERE  mac = 9729)));  

2 个答案:

答案 0 :(得分:1)

这只是代码的建议(特殊问题的答案已在P.Salmon的问题注释中)

而不是嵌套IN(subselect)的集合 您可以使用一些内部联接

select pa.str, pa.time 
from pa 
INNER JOIN con ON con.lognid = pa.conid 
INNER JOIN log ON con.lognid = log.id 
INNER JOIN phyid ON log.phyid = phyid.id AND  mac =9729  

答案 1 :(得分:0)

尝试一下:

BEGIN
    SET @macid = 9729; -- Take input from stored procedure

    SET @phyid_id = (SELECT GROUP_CONCAT(`id`) FROM `phyid` WHERE `mac` = @macid);
    SET @log_id = (SELECT GROUP_CONCAT(`id`) FROM `log` WHERE `phyid` IN(@phyid_id));
    SET @con_conid = (SELECT `conid` FROM `con` WHERE `lognid` IN(@log_id));

    SELECT `str`, `time` FROM `pa` WHERE `conid` IN(@con_conid);
END