簡體   English   中英

MySQL-為每個表選擇帶有多個表和條件的計數

[英]MySQL - Selecting Count with multiple tables and conditions for each

我想到的是一個相當簡單的查詢:

我有三個表,我想返回每個表使用的行數(有外鍵)。

這是我的第一次嘗試:

    SELECT 
        COUNT(at.code) AS atcount, 
        COUNT(de.code) AS decount, 
        COUNT(ch.code) AS chcount 
    FROM 
        table_at at, 
        table_ch ch, 
        table_de de 
    WHERE 
        at.teilnehmerid != 0
    AND
        de.teilnehmerid != 0
    AND
        ch.teilnehmerid != 0

但這在某種程度上是行不通的,它不會產生任何錯誤,但是只是不考慮條件。 我還考慮過子查詢,例如:

    SELECT 
        (SELECT COUNT(code) FROM table_at at WHERE at.teilnehmerid != 0), 
        (SELECT COUNT(code) FROM table_de de WHERE de.teilnehmerid != 0), 
        (SELECT COUNT(code) FROM table_ch ch WHERE ch.teilnehmerid != 0)

但是我對這種嘗試有些愚蠢的事情感到困惑... FROM呢? 當然,我得到一個錯誤: Operand should contain 1 column(s) -但我只想計數...

我也閱讀了有關Joins的文章,但不了解如何通過主SELECT語句中的JOIN獲取COUNT

是的,我在這里閱讀了其他一些問題,但沒有看到適用於這兩個問題的答案:

  • 選擇多個表

  • 在多個表上做一個COUNT

如果我錯了,而又沒有正確回答,也許更好的解釋會有所幫助。

COUNT (x)COUNT(DISTINCT x)非常不同。 前者對所有值進行多重計數,后者僅對不同值進行計數。 也許后者就是您要使用的。

您可能可以聯接表以獲取結果,但是卻看不到表結構及其之間的關系,這很困難。

您可以使用UNION ALL通過以下方式獲得結果:

select count(code) CodeCount, 'atcount' col
from table_at
where teilnehmerid != 0
union all
select count(code) CodeCount, 'chcount' col
from table_ch
where teilnehmerid != 0
union all
select count(code) CodeCount, 'decount' col
from table_de
where teilnehmerid != 0

這將在單個列中提供值,然后如果您希望連續顯示它們,則可以使用以下內容:

select 
    max(case when x.col = 'atcount' then x.codecount else 0 end) atcount,
    max(case when x.col = 'chcount' then x.codecount else 0 end) chcount,
    max(case when x.col = 'decount' then x.codecount else 0 end) decount
from 
(
    select count(code) CodeCount, 'atcount' col
    from table_at
    where teilnehmerid != 0
    union all
    select count(code) CodeCount, 'chcount' col
    from table_ch
    where teilnehmerid != 0
    union all
    select count(code) CodeCount, 'decount' col
    from table_de
    where teilnehmerid != 0
) x

由於COUNT()返回單行單列; 怎么樣,

SELECT * 
FROM
(SELECT COUNT(code) FROM table_at at WHERE teilnehmerid != 0) as T1, 
(SELECT COUNT(code) FROM table_de de WHERE teilnehmerid != 0) as T2, 
(SELECT COUNT(code) FROM table_ch ch WHERE teilnehmerid != 0) as T3

聯接將返回一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM