如何在 MySQL 查询中放置 IF 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/564151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:48:54  来源:igfitidea点击:

How to put IF statement in MySQL query

mysql

提问by johnnietheblack

I have a query that is simply selecting from 3 tables.

我有一个查询,它只是从 3 个表中进行选择。

  1. select from the comments table for all comments on an article

  2. select from UserID table to find what kind of user it is

  3. IF the user is one type, search one table...ELSE search another table for the final info.

  1. 从评论表中选择文章的所有评论

  2. 从 UserID 表中选择以查找它是哪种用户

  3. 如果用户是一种类型,则搜索一张表...否则搜索另一张表以获取最终信息。

How would I go about this? I'm a little new at MySQL stuff, so i totally appreciate your patience!

我该怎么办?我对 MySQL 有点陌生,所以我非常感谢你的耐心!

PS - let me know if this isnt clear...

PS - 如果这不清楚,请告诉我......

Thanks!

谢谢!

采纳答案by Nikhil

OK So lets say the type condition is - If the user if of type 'foo' search table 'foovalues' else search table 'finalvalues'.... Assuming the table structures are as follows

好的 所以假设类型条件是 - 如果用户 if 类型为 'foo' 搜索表 'foovalues' else 搜索表 'finalvalues'.... 假设表结构如下

Comments CommentID UserID ArticleID

评论 CommentID UserID 文章ID

Users UserID UserType

用户 UserID UserType

 Declare TestUserType varchar(3);

 select * from Comments where ArticleID = <inputid>; //Returns the comments 

 select TestUserType = UserType from Users where UserID = <inputuser>; //Returns the usertype for a user and assigns it to a variable

 if TestUserType = 'foo' 
   begin 
    select * from FooValues;
   end
 else
   begin 
    select * from FinalValues;
   end 

Disclaimer: The above SQL should work in mySQL but it's been awhile since I worked on that DB and I don't have access to it right now so the SQL above may encounter syntax errors.

免责声明:上面的 SQL 应该可以在 mySQL 中工作,但是自从我在那个数据库上工作已经有一段时间了,我现在无法访问它,所以上面的 SQL 可能会遇到语法错误。

You can put the SQL in a stored proc as well - if you are doing that mySQL has this thing about delimiters you might want to look out for - I blogged about it here

你也可以把 SQL 放在一个存储过程中——如果你这样做的话,mySQL 有关于分隔符的东西,你可能想要注意——我在这里写了博客

回答by user64075

I wouldn't put them all in a single query. The code is much more readable if you break the operation down to smaller steps.

我不会将它们全部放在一个查询中。如果将操作分解为更小的步骤,代码的可读性会更高。

If performance is not a concern, you could get the user type first and then run another query depending on the type.

如果性能不是问题,您可以先获取用户类型,然后根据类型运行另一个查询。

For a more correct way, you should consider using a stored procedure.

对于更正确的方法,您应该考虑使用存储过程。