MySQL - 查询中 IF...ELSE 用法的帮助

发布于 2024-11-07 22:45:38 字数 356 浏览 0 评论 0原文

我需要在 MySQL 查询中添加 if/else 语句,但无法使其工作。

下面是一个带有我想要完成的伪代码的示例。

SELECT *
FROM calendar
WHERE calendar.alert = 1

IF calendar.repeat = 0 THEN HAVING calendar.UTC_1 > UNIX_TIMESTAMP();

ELSE "get all records regardless of calendar.repeat value";

END IF;

有什么建议可以实现这一点吗?我找不到这个 MySQL IF ELSE 的正确语法。

感谢您的帮助!

I need to add an if/else stament inside a MySQL query but can't get it to work.

Below is an example with pseudo-code of what I want to accomplish.

SELECT *
FROM calendar
WHERE calendar.alert = 1

IF calendar.repeat = 0 THEN HAVING calendar.UTC_1 > UNIX_TIMESTAMP();

ELSE "get all records regardless of calendar.repeat value";

END IF;

Any suggestions to make this happen? I couldn't find the correct syntax for this MySQL IF ELSE.

Thanks for helping!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜味超标? 2024-11-14 22:45:38
SELECT *
FROM calendar
WHERE calendar.alert = 1 
AND CASE 
WHEN `repeat` =0 THEN UTC_1 > UNIX_TIMESTAMP()
ELSE 1=1 END;

您只能在存储过程/触发器体内使用 IF-ELSE。您可以在 SELECT 中使用 IF(condition, value_if_condition_is_true, value_if_condition_is_false),但我更喜欢 CASE(您可以轻松地将上面的查询重写为

 .... AND IF(`repeat` = 0, UTC_1>UNIX_TIMESTAMP(),1=1)
SELECT *
FROM calendar
WHERE calendar.alert = 1 
AND CASE 
WHEN `repeat` =0 THEN UTC_1 > UNIX_TIMESTAMP()
ELSE 1=1 END;

You can use IF-ELSE only inside the body of stored procedure/trigger. You can use IF(condition, value_if_condition_is_true, value_if_condition_is_false) in SELECT, but I prefer CASE(you can easily rewrite the query above to

 .... AND IF(`repeat` = 0, UTC_1>UNIX_TIMESTAMP(),1=1)
月亮邮递员 2024-11-14 22:45:38

不确定我在这里的语法是否正确,但我喜欢这样的想法。在我看来,将来通过以下示例查看您所抓住的两个组会更容易。我没有受过有关 MySQL 中 case 与 union 的效率方面的教育,但在我看来,case 的效率也会较低。也许有人可以肯定地回答这个问题?

SELECT *
FROM calendar
WHERE 
    calendar.alert = 1
    AND calendar.repeat = 0
    AND calendar.UTC_1 > UNIX_TIMTESTAMP();
UNION
SELECT *
FROM calendar
WHERE
    calendar.alert = 1
    AND calendar.repeat != 0

Not sure I got the syntax all right here, but I like the idea of somethign like this. In my opinion it is much easier to look at in the future and see the two groups you're grabbing with the following example. I'm not educated on efficiency of case vs union in MySQL but it seems to me like the case would be less efficient as well. Maybe someone can answer that for sure?

SELECT *
FROM calendar
WHERE 
    calendar.alert = 1
    AND calendar.repeat = 0
    AND calendar.UTC_1 > UNIX_TIMTESTAMP();
UNION
SELECT *
FROM calendar
WHERE
    calendar.alert = 1
    AND calendar.repeat != 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文