MySQL - 存储过程 - 联合选择然后更新和插入
我需要创建一个 MYSQL 存储过程,它将使用 UNION 查询在五个表之一中查找电子邮件地址。一旦找到电子邮件地址,存储过程需要更新原始表中的字段,并将信息插入到另一个表中。
这是我的联合:
SELECT email, 'table1' AS nameoftable, status FROM table1
WHERE email = '[email protected]'
UNION
SELECT email, 'table2' AS nameoftable, status FROM table2
WHERE email = '[email protected]'
UNION
SELECT email, 'table3' AS nameoftable, status FROM table3
WHERE email = '[email protected]'
这应该返回一条记录,这将为我提供后续步骤中需要的 nameoftable 变量,例如: [email protected] table1 A
首先插入: INSERT INTO 黑名单(电子邮件、表名、已添加) SELECT email、'nameoftable'、已添加 FROM nameoftable WHERE email = '[电子邮件受保护]';
然后更新: UPDATE nameoftable SET status = 'D' WHERE email = '[电子邮件受保护] ';
当然,如果没有记录,程序就应该退出。
因此,我试图将这一切整合到一个存储过程中。此存储过程将与电子邮件程序一起使用,该程序将根据请求从各种列表中删除电子邮件。现在,我正在用手做,这变得很乏味。
我将不胜感激任何指示或想法。提前致谢。
I need to create a MYSQL stored procedure which will use a UNION query to find an email address in one of five tables. Once the email address is found, the stored procedure needs to update a field in the original table, and insert the information into another table.
Here's my union:
SELECT email, 'table1' AS nameoftable, status FROM table1
WHERE email = '[email protected]'
UNION
SELECT email, 'table2' AS nameoftable, status FROM table2
WHERE email = '[email protected]'
UNION
SELECT email, 'table3' AS nameoftable, status FROM table3
WHERE email = '[email protected]'
This should return one record, which will give me the nameoftable variable that I need in the next steps eg:
[email protected] table1 A
First the insert:
INSERT INTO blacklist (email, tablename, added) SELECT email, 'nameoftable', added FROM nameoftable WHERE email = '[email protected]';
Then the update:
UPDATE nameoftable SET status = 'D' WHERE email = '[email protected]';
Of course, if there is no record, the procedure should quit.
So, I am trying to roll this all into one stored procedure. This stored procedure is going to be used with an email program that will remove emails from various lists upon request. Right now, I'm doing it by hand, and it's getting tedious.
I would appreciate any pointers or ideas. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题似乎是变量中有一个表名,但您需要将该变量的值转换为标识符,以便您可以用它执行正常的 SQL 操作。你可以做一些丑陋的事情:
或者你可以使用准备好的语句(其中或多或少是一种形式of
eval
):我非常确定
CONCAT
可以在该上下文中工作,但如果不能,您可以将 SQL 构建为变量并PREPARE that:
一旦您解决了将变量的值转换为 SQL 标识符的问题,您的过程的其余部分似乎就非常简单了。
Your problem seems to be that you have a tablename in a variable but you need to turn the value of that variable into an identifier so that you can do normal SQL things with it. You could so something somewhat ugly like this:
Or you could use a prepared statement (which is, more or less, a form of
eval
):I'm pretty sure that the
CONCAT
will work in that context but if not, you can build the SQL as a variable andPREPARE
that:The rest of your procedure seems pretty straight forward once you get over the problem of converting a variable's value to an SQL identifier.