[英]Optimization for SQL Select with Union
I have the following SQL query, in which I make use of UNIONs:我有以下 SQL 查询,其中我使用了 UNION:
SELECT notification FROM NotificationDb notification WHERE notification.proc_name = 'a' AND notification.status = 1 AND notification.module = 1
UNION
SELECT notification FROM NotificationDb notification WHERE notification.proc_name = 'b' AND notification.param1 >0 AND notification.status = 1 AND notification.module = 1
UNION
SELECT notification FROM NotificationDb notification WHERE notification.proc_name = 'b' AND notification.param1 <= 0 AND notification.status = 1 AND notification.module = 1
I have it set up this way, because I need them ordered by proc_name field and also param1 value for cases where proc_name is 'b'我以这种方式设置它,因为我需要它们按 proc_name 字段排序,并且还需要在 proc_name 为“b”的情况下使用 param1 值
QUESTION: Is there a better, a more efficient way of putting together a query that would return the same result?问题:有没有更好、更有效的方法来组合一个返回相同结果的查询?
Any help would be appreciated!任何帮助,将不胜感激!
If I understand correctly, you don't need unions here, you can just do a single distinct select:如果我理解正确,您在这里不需要联合,您可以只做一个不同的 select:
SELECT DISTINCT notification
FROM NotificationDb
WHERE status = 1 AND module = 1 AND proc_name IN ('a', 'b')
ORDER BY
proc_name,
param1 DESC;
Here, we add an ORDER BY
clause which puts a
proc_name
records before b
.在这里,我们添加了
a
ORDER BY
子句,它将proc_name
记录放在b
之前。 Then, within all b
records, we show larger param1
records first.然后,在所有
b
条记录中,我们首先显示较大的param1
记录。 This sorting maintain the perceived ordering you have in current union query (though it should be noted that no such actual order is there; always use an ORDER BY
clause if you expect a certain sorting in your result set).这种排序保持您在当前联合查询中的感知顺序(尽管应该注意没有这样的实际顺序;如果您希望在结果集中进行某种排序,请始终使用
ORDER BY
子句)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.