Jump to content
php.lv forumi

luugums peec sql pieprasiijuma


andrisp

Recommended Posts

Ir divas tabulas - vienaa glabaajaas ieraksti par materiaaliem, otraa - informaacija par iepirkshanas un izlietoshanas operaacijaam shiem pashiem materiaaliem.

 

Struktuura apt. shaada: (Te ir iistaa structuura)

 

MATERIALI

id | name | critical_quantity

 

OPERACIJAS

id | materiala_id | operation_type | amount

 

//operation_type - enum('in', 'out');

 

Meegjinu uzrakstiit sql pieprasiijumu, kas sasumme attieciigaa materiala_id visas ' amount' veertiibas, kur operation_type ir 'in', un arii attieciigi sasummee operation_type = 'out' operaacijas attieciigam materiala_id. Peec tam atnjem shiis veertiibas un saliidzina ar critical_quantity no MATERIALI. Ja ir mazaaks, tad atgriezh rezultaa.

 

Pats esmu izburtojis kaut ko shaadu, bet negrib straadaat:

SELECT 
m.id, m.name, m.critical_quantity
FROM
materiali_operacijas as i, materiali_operacijas as o, materiali as m
WHERE
i.operation_type = 'in' AND o.operation_type = 'out' AND m.id = i.materiala_id AND m.id = o.materiala_id
HAVING
m.critical_quantity <= (SUM(i.amount) - SUM(o.amount))

 

Paliidzeesiet, luudzu ?

Link to comment
Share on other sites

SELECT m.id, m.name, m.critical_quantity
FROM materiali as m
JOIN (SELECT materiala_id , SUM(IF(operation_type="in", +1, -1)*amount) as amount FROM operacijas GROUP BY materiala_id) as ops ON m.id = ops.materiala_id
WHERE m.critical_quantity <= ops.amount

Link to comment
Share on other sites

×
×
  • Create New...