Jump to content
php.lv forumi

Count & join & distinct


Infants

Recommended Posts

Problēma jau atrisināta, varbūt kādam arī ir bijusi šāda problēma (vai arī vēl tikai būs).

Ir 3 tabulas:

Tabula t1
id      1 |    2 |    3 |    4
name kat1 | kat2 | kat3 | kat4

Tabula t2
id   	1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
t1_id   1 | 1 | 2 | 2 | 2 | 2 | 3 | 3 | 3

Tabula t3
id   	1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
t1_id   1 | 1 | 2 | 2 | 2 | 2 | 2 | 2 | 3

 

No šī vajadzēja dabūt rezultātu:

     id    1 |    2 |    3 |    4
   name kat1 | kat2 | kat3 | kat4
t2_count    2 |    4 |    3 |    0
t3_count    2 |    6 |    1 |    0

Sākumā pārbaudu pielikt t2 skaitu

SELECT
t1.*,
COUNT(t2.id) as t2_count
FROM 	t1
LEFT JOIN 		t2 ON t1.id = t2.t1_id
GROUP BY t1.id

Ar 1 join strādā baigi forši, bet tiklīdz pieliek otru join:

SELECT
t1.*,
COUNT(t2.id) as t2_count,
COUNT(t3.id) as t3_count
FROM 	t1
LEFT JOIN 		t2 ON t1.id = t2.t1_id
LEFT JOIN 		t3 ON t1.id = t2.t1_id
GROUP BY t1.id

nekas vairs nestrādā.

Ar šito nočakarējos diezgan ilgu laiku, gribēju jau te bļaut, kas, kāpēc, ko darīt, kā darīt. Google tika izrakāta.

Beigās izrādījās, ka vajag likt COUNT(DISTINCT).

SELECT
t1.*,
COUNT(DISTINCT t2.id) as t2_count,
COUNT(DISTINCT t3.id) as t3_count
FROM 	t1
LEFT JOIN 		t2 ON t1.id = t2.t1_id
LEFT JOIN 		t3 ON t1.id = t3.t1_id
GROUP BY t1.id

Un viss strādā, gaidītais rezultāts parādās.

 

P.s. Varbūt kāds var iekomentēt, kāpēc, ja ir 1 join tabula,count() strādā korekti, bet tiklīdz 2 joini, rezultāts tiek sačakarēts?

Tā, kā neesmu nekāds pro, varbūt te vēljoprojām kaut kas ir nepareizi, un kļūdas parādīsies?

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...