left-join把查询搞砸了

lmyy7pcs  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(312)

我对此查询有一些问题,它没有按原样返回所有行:

SELECT DE.user_id, 
       DE.id, 
       DE.title, 
       DE.limit_new_cards, 
       DE.limit_old_cards, 
       DE.deleted, 
       Count(DISTINCT TCA.id) total_cards, 
       Count(DISTINCT NCA.id) new_cards, 
       Count(DISTINCT OCA.id) due_cards 
FROM   decks AS DE 
       LEFT JOIN cards AS TCA 
              ON TCA.deck_id = DE.id 
       LEFT JOIN cards AS NCA 
              ON NCA.deck_id = DE.id 
                 AND NCA.is_new = 1 
       LEFT JOIN cards AS OCA 
              ON OCA.deck_id = DE.id 
                 AND OCA.due_date <= CURRENT_DATE() 
WHERE  DE.user_id = 47 
GROUP  BY TCA.deck_id 
ORDER  BY DE.id;

它是否应该返回与此查询相同的行数?还是不?

SELECT user_id, 
       id, 
       title, 
       limit_new_cards, 
       limit_old_cards, 
       deleted, 
FROM   decks 
WHERE  user_id = 47 
ORDER  BY id;

如果有人能帮我,我会很高兴的。

kgqe7b3p

kgqe7b3p1#

我怀疑问题出在你身上 GROUP BY 条款:

GROUP BY TCA.deck_id

应该是:

GROUP BY DE.id

理论基础: TCA 是一个 LEFT JOIN 具有以下条件的ed表:

ON TCA.deck_id = DE.id

没有对手的时候 TCA , TCA.deck_idNULL ,那你呢 GROUP BY . 所以你最终得到了 DE.id 没有对手的 TCA 组合在一起。相反,您应该使用基表中相应的列 DE -想必,这是永远不会发生的 NULL .

相关问题