Parte del tuo problema è che stai usando una funzione aggregata nell'elenco SELECT ma non stai usando un GROUP BY
. Dovresti utilizzare un GROUP BY
simile a questo:
GROUP BY d.testId, d.rowId
Ogni volta che utilizzi una funzione di aggregazione e hai altre colonne nella tua selezione, dovrebbero essere in un gruppo per. Quindi la tua query completa dovrebbe essere:
select d.testId,
d.rowId,
max(if(f.keyName='voltage',f.keyValue,NULL)) as 'voltage',
max(if(f.keyName='temperature',f.keyValue,NULL)) as 'temperature',
max(if(f.keyName='velocity',f.keyValue,NULL)) as 'velocity'
from tests t
inner join data d
on t.testId = d.testId
inner join data c
on t.testId = c.testId
and c.rowId = d.rowId
join data f
on f.testId = t.testId
and f.rowId = d.rowId
where (d.keyName = 'voltage' and d.keyValue < 5)
and (c.keyName = 'temperature' and c.keyValue = 30)
and (t.testType = 'testType1')
GROUP BY d.testId, d.rowId
Nota, mentre la tua effettiva struttura dei dati non è presentata nella tua domanda originale. Sembra che questo possa essere consolidato come segue:
select d.testid,
d.rowid,
max(case when d.keyName = 'voltage' and d.keyValue < 5 then d.keyValue end) voltage,
max(case when d.keyName = 'temperature' and d.keyValue =30 then d.keyValue end) temperature,
max(case when d.keyName = 'velocity' then d.keyValue end) velocity
from tests t
left join data d
on t.testid = d.testid
group by d.testid, d.rowid
Vedi SQL Fiddle con demo
. Questo dà il risultato con un solo join ai data
tabella:
| TESTID | ROWID | VOLTAGE | TEMPERATURE | VELOCITY |
-----------------------------------------------------
| 1 | 1 | 4 | 30 | 20 |
| 1 | 2 | 4 | 30 | 21 |
| 2 | 1 | 4 | 30 | 30 |
| 2 | 2 | 4 | 30 | 31 |