简体   繁体   English

MySQL在一个查询中同时选择SUM和同一列的一个特定行-最佳方式?

[英]MySQL select both SUM and one specific row of the same column in one query - optimal way?

Well, the question might not seem very smart, since I solve my problem. 好吧,因为我已经解决了问题,所以这个问题似乎不太明智。 I'm just curious if there is better way. 我只是好奇是否有更好的方法。 I wrote this query: 我写了这个查询:

SELECT 
    SUM(`attr`) AS `attrsum`, 
    (SELECT `attr` FROM `table`
     WHERE `id`=XXX AND `specialcondition`=YYY) AS `attr` 
FROM 
    `table` 
WHERE 
    `id`=XXX

It absolutely works and do what I want, but I'm not sure - is it the best way to do this? 它绝对可以运行并且可以执行我想要的操作,但是我不确定-这是最好的方法吗? I mean subquery is still like another query, so I doubt that this is the optimized way to get those data. 我的意思是子查询仍然像另一个查询,因此我怀疑这是获取这些数据的优化方法。 On the other hand - I have no idea how it can be done better. 另一方面-我不知道如何做得更好。 Or this is the best way and everything is fine in my query? 还是这是最好的方法,我的查询一切都很好?

Assumming that the subquery is retrieving a single row, you can eliminate the subquery using MAX or MIN aggregate function together with CASE expression in this way: 假设子查询正在检索单个行,则可以通过以下方式使用MAX或MIN聚合函数以及CASE表达式消除子查询:

SELECT 
    SUM(`attr`) AS `attrsum`, 
    MAX( CASE WHEN `specialcondition`=YYY THEN `attr` END ) as `attr` 
FROM `table` WHERE `id`=XXX

A speed gain will depend on the number of records in the table for a single ID, if it's only a few hundred records, it will be unnoticeable, for millions of records without an multicolumn index on (id, specialcondition) can be significant. 速度的提高取决于单个ID的表中记录的数量,如果只有几百条记录,则不会引起注意,因为数百万个没有多列索引(id, specialcondition)可能很重要。
For the above query, a simple index on id column is sufficient. 对于上面的查询,在id列上的简单索引就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM