Jump to content
php.lv forumi

SELECT join ...


reiniger

Recommended Posts

Sveiki.

 

Nepieciešams padoms.

 

Man ir jaatlasa ieraksti kur konkretas colonas starpiba nav nulle.

Uzrakstišu vienkāršotu piemēru, jo manas tabulas ir diezgan sarežģītas un grūti būs saprast ko man vajag panākt. :)

 

Piemērs

tabula1  // noliktavas tabula
t1ID | val | title
 1  |  1  | nol1
 2  |  1  | nol2
 3  |  1  | nol3
 4  |  2  | nol4

tabula2  // burkānu kastes konkreta noliktava
t2ID | t1ID | burk
 1  |  1   |  6
 2  |  1   |  5
 3  |  2   |  2
 4  |  2   |  2
 5  |  3   |  3
 6  |  4   |  9

tabula3  // izvestais burkanu daudzums no kastes
t3ID | t2ID | burk
 1  |  1   |  4
 2  |  2   |  2
 3  |  3   |  2
 4  |  4   |  1

Man ir nepieciešams pēc tabula1.val = 1 atlasīt, kur vēl ir palikuši burkāni.

SELECT t2.t2ID, t1.title, t2.burk-SUM(t3.burk) AS atlburk
FROM tabula1 AS t1 
JOIN tabula2 AS t2 ON (t2.t1ID=t1.t1ID) 
JOIN tabula3 AS t3 ON (t3.t2ID=t2.t2ID)  
WHERE t1.val = 1
GROUP by t2.t2ID 
HAVING atlburk != 0

SUM nepieciešams, jo var būt vairāki izvesti gadīju no konkrētas kastes

It kā viss strādā pareizi.

Rezultāts

t2id |  title| atlburk
 1  |  nol1 | 2
 2  |  nol1 | 3
 4  |  nol2 | 1

Problēma sakas tad, kad tabula3 nav ieraksta ar tabula2.t2ID vērtību! Kur val ir 2 tad table2.t2ID 6 ir 9, bet nav vertību, ko atņemt no tabula3 un šī kaste neparādas sarakstā, ka tajā ir burkāni!

 

Kā panākt to, ja nav šads ieraksts iekš tabula3, tad ta vieta atņemas 0!

Edited by reiniger
Link to comment
Share on other sites

Prieks ka ir kur uzjautāt grūtos gadījumos. Paldies.

 

Šādi viss strādā, ja kādam vajag.

SELECT t2.t2ID, t1.title, t2.burk-COALESCE(SUM(t3.burk),0) AS atlburk
FROM tabula1 AS t1 
LEFT JOIN tabula2 AS t2 ON (t2.t1ID=t1.t1ID) 
LEFT JOIN tabula3 AS t3 ON (t3.t2ID=t2.t2ID)  
WHERE t1.val = 1
GROUP by t2.t2ID 
HAVING atlburk != 0

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...