vendredi 8 mai 2015

SQL request and loop trough result best pattern (Java)

I didn't really know a good title for this but I'm asking myself what would be considered "good" for the following scenario

Table Place: id / name / address / etc

Table Tag: id / tag_name / score

Table Place_Tag id / place_id / tag_id / numberX

For example, my application allow a user to search a place based on a tag. the result should contain the name of the place as well as the top 3 tag for that place (ordered by numberX)

My question is what is the best way to achieve this in Java using SQL ?

1) Select p.name, t.tag_name FROM Place p LEFT JOIN ... GROUP BY p.name,t.tag_name ORDER BY p.id,pt.numberX DESC

And then in Java I loop though the result (note the ORDER BY p.id) create some logic to only get the top 3 tag and when I detected that the n+1 id is different that means I'm processing the next place..

2) places = SELECT DISTINCT p.name FROM..... ORDER BY p.id
   tags = SELECT ... FROM Place_Tag pt WHERE pt.place_id IN (places.ids)

I make two separate SQL call one to get the places one to get the tags and then I find some kind of logic to link both together in Java

3 (this is the easier but I think the worst) ) places = Select p.name FROM Place...

and then I loop through places and make a call to the database to get its tag (meaning if I loop trough 100 place I will make 100 extra call everytime..)

4) ? any other pattern ?

Could someone with more experience alive me on this?

Thank you!

Aucun commentaire:

Enregistrer un commentaire