Amir
Amir

Reputation: 199

sql many to many select with join

I am trying to make a select statement and I just cant get it work.

I have 3 tables: places, tags, places_tags

Places:
   - id
   - name

Tags:
   - id
   - name

Places_tags:
   - place_id
   - tag_id
   - order

I am trying to select places and join the first tag that inserted (using order)

        SELECT p.*, t.tag_id AS tag
        FROM `places` as p
        LEFT JOIN places_tags t ON (t.place_id = p.id)
        group by p.id

That's what I have right now. I need to add somthing like ORDER BY order DESC...

I think that I'm not doing it right.

Upvotes: 0

Views: 393

Answers (1)

btiernay
btiernay

Reputation: 8129

Something like the following should work:

SELECT 
   p.name AS "place", 
   t.name AS "firstTag" 
FROM 
   places p 
   LEFT JOIN
   places_tags pt1 
      ON pt1.place_id = p.id
   LEFT JOIN
   places_tags pt2 
      ON pt2.place_id = p.id AND pt2.tag_id < pt1.tag_id
   LEFT JOIN 
   tags t 
      ON t.id = pt1.tag_id
WHERE
   pt2.tag_id IS NULL

Upvotes: 0

Related Questions