我有一个像下面这样的 mysql 查询。
select new,processing,close
from
(select count(id) new from tickets where id_client in (_a_list_of_client_id) and status = new),
(select count(id) processing from tickets where id_client in (_a_list_of_client_id) and status = processing),
(select count(id) close from tickets where id_client in (_a_list_of_client_id) and status = close)
以下不是精确查询而是伪查询
这里 _a_list_of_client_id 是另一个查询,如下所示 从客户端选择 id_client where id_user = {some_id_given_as_parameter}
我只是想知道在一个查询中多次使用相同的子查询是否是正确的方法。或者有没有其他方法可以做这样的事情。
提前致谢 MH拉塞尔
最佳答案
您可以将sum
与case
一起使用,并将子查询移动到where
条件:
select
sum(case when status = 'new' then 1 else 0 end) new,
sum(case when status = 'processing' then 1 else 0 end) processing,
sum(case when status = 'close' then 1 else 0 end) close
from tickets
where id_client in (_a_list_of_client_id)
还有一些其他方法可以做到这一点(例如使用 if
或省略 case
),但我认为这很容易阅读。例如,我相信 mysql 可以使用 sum(status='new')
。
关于mysql - 在 mysql 查询中多次相同(子)查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19683671/