[英]How to combine multiple counts from different tables in one mysql query?
我有一些不同的查詢來獲取一些計數器。 是否可以將這些查詢合並為一個,但不能匯總和合並計數器?
例如:
SELECT
COUNT(uuid) AS total_admins ta,
SUM(CASE WHEN isPublished = 1 THEN 1 ELSE 0 END) AS total_admins_published tap,
SUM(CASE WHEN isPublished = 0 THEN 1 ELSE 0 END) AS total_admins_unpublished tau
FROM admins
和
SELECT
COUNT(uuid) AS total_mediators tm,
SUM(CASE WHEN isPublished = 1 THEN 1 ELSE 0 END) AS total_mediators_published tmp,
SUM(CASE WHEN isPublished = 0 THEN 1 ELSE 0 END) AS total_mediators_unpublished tmu
FROM mediator
和
SELECT
COUNT(uuid) AS total_posts tp,
SUM(CASE WHEN submissionDate BETWEEN "start" AND "end" THEN 1 ELSE 0 END) AS total_posts_week tpw,
SUM(CASE WHEN submissionDate BETWEEN "start" AND "end" THEN 1 ELSE 0 END) AS total_posts_month tpm,
SUM(CASE WHEN submissionDate BETWEEN "start" AND "end" THEN 1 ELSE 0 END) AS total_posts_year tpy
FROM posts
我的期望是:
| ta | tap | tau | tm | tmp | tmu | tp | tpw | tpm | tpy |
|----|-----|-----|----|-----|-----|-----|-----|-----|-----|
| 20 | 10 | 10 | 12 | 10 | 2 | 230 | 30 | 180 | 220 |
您可以CROSS JOIN
連接三個查詢:
SELECT ta, tap, tau, tm, tmp, tmu, tp, tpw, tpm, tpy
FROM (
SELECT
COUNT(uuid) AS total_admins ta,
SUM(CASE WHEN isPublished = 1 THEN 1 ELSE 0 END) AS total_admins_published tap,
SUM(CASE WHEN isPublished = 0 THEN 1 ELSE 0 END) AS total_admins_unpublished tau
FROM admins
) a
CROSS JOIN (
SELECT
COUNT(uuid) AS total_mediators tm,
SUM(CASE WHEN isPublished = 1 THEN 1 ELSE 0 END) AS total_mediators_published tmp,
SUM(CASE WHEN isPublished = 0 THEN 1 ELSE 0 END) AS total_mediators_unpublished tmu
FROM mediator
) m
CROSS JOIN (
SELECT
COUNT(uuid) AS total_posts tp,
SUM(CASE WHEN submissionDate BETWEEN "start" AND "end" THEN 1 ELSE 0 END) AS total_posts_week tpw,
SUM(CASE WHEN submissionDate BETWEEN "start" AND "end" THEN 1 ELSE 0 END) AS total_posts_month tpm,
SUM(CASE WHEN submissionDate BETWEEN "start" AND "end" THEN 1 ELSE 0 END) AS total_posts_year tpy
FROM posts
) p
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.