Question

This is my table (table1):

id | code | tid | iid |
1  | xx   | 0   | 1   |
2  | xx   | 1   | 0   |

Now if I do the SQL

'SELECT * FROM 'table1' LEFT JOIN 'table_t' ON 'table_t'.'id' = 'table1'.'tid' LEFT JOIN 'table_i' ON 'table_t'.'id' = 'table1'.'iid' GROUP BY 'code'

Now when I search for the the code 'xxx' and LEFT JOIN the other 2 table's here, the JOIN will JOIN the '0' from the tid, but I want to JOIN the '1' (or just the highest number). Does anyone have a good (and fast) SQL for this? Or is it even possible?

I also made a very simple SQLfiddle of it: http://sqlfiddle.com/#!2/d10bc6/1

I need something like this:

SELECT * 
from jointable j 
left join tid_table t on t.id = MAX(j.tid) 
left join iid_table i on i.id = MAX(j.iid)
group by code

Hope someone can help, I have been searching and trying for hours.

edit As you see in the demo, I'm getting "null" for tid_naam, this should be tid-name

Était-ce utile?

La solution

You are using group by but without any aggregate function so use MAX() this will resolve the problem to get the highest value for you field

select j.id,j.code,MAX(j.tid)tid,MAX(j.iid) iid ,
t.*,i.*
from jointable j 
left join tid_table t on t.id = j.tid 
left join iid_table i on i.id = j.iid
group by code

If you want to search for your code you can do so See search demo

Demo

Other way you can use a subselect based on the maxima your columns

select j.id,j.code,MAX(j.tid)tid,MAX(j.iid) iid ,
t.*,i.*
from 
(SELECT id,code,MAX(tid)tid,MAX(iid) iid FROM jointable group by code)
 j 
left join tid_table t on t.id = j.tid 
left join iid_table i on i.id = j.iid
group by code

Demo

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top