0

I have these tables

Irasai table

invoice_nr | pard_suma | pard_vad | pirk_vad
1122         200         2,4,6      2,1,3
1111         502,22      3          4
1112         5545        3          4,1
54151        1000        2          1
74411        1345,78     6          18

Apmokejimai table:

id | invoice_nr | suma | tipas
1    1122         100    2
2    1112         5545   1
3    1122         100    2
4    1111         310    2
5    54151        200    2

This query:

select t1.invoice_nr, max(t1.pard_suma) as pardtotal, sum(t2.suma) as sumatotal 
from irasai t1 
left join apmokejimai t2 on t1.invoice_nr = t2.invoice_nr 
WHERE t2.tipas != '1' 
    OR t2.tipas IS NULL  
    AND FIND_IN_SET(1, t1.pirk_vad) 
    OR FIND_IN_SET(1, t1.pard_vad) 
group by invoice_nr 
having pardtotal <> sumatotal or sumatotal is null

Result is this:

invoice_nr | pard_total | sumtotal
1111         502.22       310
54151        1000         200

Should be like this

invoice_nr | pard_total | sumtotal
54151        1000         200

I need to get this because it belongs to user which id is 1

Rytis
  • 59
  • 8

2 Answers2

1

You need to group the conditions in your WHERE clause with parentheses.

select t1.invoice_nr, max(t1.pard_suma) as pardtotal, sum(t2.suma) as sumatotal 
from irasai t1 
left join apmokejimai t2 on t1.invoice_nr = t2.invoice_nr 
WHERE (t2.tipas != '1' 
       OR t2.tipas IS NULL)  
    AND (FIND_IN_SET(1, t1.pirk_vad) 
        OR FIND_IN_SET(1, t1.pard_vad))
group by invoice_nr 
having pardtotal <> sumatotal or sumatotal is null

DEMO

Without parentheses, AND has higher precedence than OR, so it's interpreted as

WHERE t2.tipas != 1 
    OR (t2.tipas IS NULL 
        AND 
        FIND_IN_SET(1, t1.pirk_vad))
    OR FIND_IN_SET(1, t1.pard_vad)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I modified your SQL. These will work.

select invoice_nr, max(pardtotal), sumatotal  from (
    select t1.invoice_nr, max(t1.pard_suma) as pardtotal, sum(t2.suma) as sumatotal 
    from irasai t1 
    left join apmokejimai t2 on t1.invoice_nr = t2.invoice_nr 
    WHERE t2.tipas != '1' 
        OR t2.tipas IS NULL  
        AND FIND_IN_SET(1, t1.pirk_vad) 
        OR FIND_IN_SET(1, t1.pard_vad) 
    group by invoice_nr having pardtotal <> sumatotal or sumatotal is null 
) a

Thank you.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Venkatesh Panabaka
  • 2,064
  • 4
  • 19
  • 27
  • Not working, now I'm getting one row that invoice is 1111, I need to get 54151 because it belogs to 1(id) pirk_vad or pard_vad, 1111 invoice didn't belogs to that user. – Rytis Jul 31 '15 at 07:32