2009-03-26 5 views
1

MySql 쿼리 도움말 : 합계 및 개수가있는 연결

TBL_A | TBL_B | TBL_C | TBL_D | TBL_E 
-------+---------+---------+---------+---------- 
id  | id_tbla | id_tbla | id_tbla | id 
name | id_user | id_user | id_user | name_tbla 
... | is_bool |   | weight | id_user 

다음은 내가 성취하려는 것입니다.

SELECT 
    a.id, 
    a.name, 
    b.is_bool, 
    count(c.id_user) AS nb_views, 
    sum(d.weight) AS total_weight, 
    count(distinct e.id_user) AS distinct_users, 
FROM TBL_A AS a 
LEFT JOIN (TBL_B AS b) on (b.id_tbla = a.id) 
LEFT JOIN (TBL_C AS c) on (c.id_tbla = a.id) 
LEFT JOIN (TBL_D AS d) on (d.id_tbla = a.id) 
LEFT JOIN (TBL_E AS e) on (e.name_tbla = a.name) 
where a.id = 1 and e.id_user = 1 

쿼리가 수행되었지만 결과 (nb_views, total_weight, distinct_users)가 잘못되었습니다. 왜 그런가?

답변

1

하나의 쿼리에서 너무 많은 집계를 계산하려고합니다.

Enita 비 sunt multiplicanda praeter necessitatem

내 테이블 B, C, D 및 E

가 생성된다 (라틴 "엔티티 필요 이상으로 승산되는 것은 아니다") Cartesian Products.

  • 3 행 B에서
  • 6 행 C에
  • 4 행 D에
  • 행 1 E

의 총 수의 경우 a에서 주어진 행 일치한다고 가정 결과의 행은 3 * 6 * 4 * 1 = 72 행입니다. 그래서 count(c.id_user)

가장 간단한 해결책은 별도의 쿼리에서 이러한 집계의 각을 계산하는 등, 당신의 sum(d.weight)은 그것이 있어야 무엇 18 배, 그것이 있어야 무엇을 12 배 :

SELECT a.id, a.name, COALESCE(b.is_bool, FALSE) AS is_bool 
FROM TBL_A AS a LEFT JOIN TBL_B AS b ON (b.id_tbla = a.id) 
WHERE a.id = 1; 

SELECT a.id, COUNT(c.id_user) AS nb_views 
FROM TBL_A AS a LEFT JOIN TBL_C AS c ON (c.id_tbla = a.id) 
WHERE a.id = 1; 

SELECT a.id, SUM(d.weight) AS total_weight, 
FROM TBL_A AS a LEFT JOIN TBL_D AS d ON (d.id_tbla = a.id) 
WHERE a.id = 1; 

SELECT a.id, COUNT(DISTINCT e.id_user) AS distinct_users, 
FROM TBL_A AS a LEFT JOIN TBL_E AS e 
    ON (e.name_tbla = a.name AND e.id_user = 1) 
WHERE a.id = 1; 
+0

딱! 당신은 내가 요청한 숫자를 이해하도록 도왔습니다. 나는 그 때 4 개의 요구를 할 것이다! 몇 시간 동안 한 번에 모든 것을하려고 노력하는 것 때문에 많은 ... :) – karlipoppins