tags:

views:

158

answers:

3

Hello,

I have 3 tables: people, groups and memberships. Memberships is a join table between people and groups, and have 3 columns: personId, groupId and description (text).

I want to select entries from the memberships table depending on a groupId but sorting the result by the names of people associated to the found memberships (name is a column of people table)

SELECT * FROM "memberships" WHERE ("memberships".groupId = 32) ORDER BY (?????)

Is it possible to achieve this in one single query?

+3  A: 

Join to the people table and then order by the field that you want.

SELECT
  m.* 
FROM 
  "memberships" AS m
  JOIN "people" AS p on p.personid = m.personID
WHERE
  m.groupId = 32
ORDER BY 
  p.name
Donnie
Some SQL data servers insist that you order by selected data only - in which case, you'd have to add p.name to the selected data.
Jonathan Leffler
+1  A: 
SELECT *
FROM Membership AS m
     JOIN People as p ON p.personID = m.personID
WHERE m.groupID = 32
ORDER BY p.name
Damir Sudarevic
It appears he wants the information from the memberships table only, so maybe "SELECT m.* ...as above..."? Then it depends on the SQL data server whether you can order by a non-selected column; if not, then the returned data will have to include p.name.
Jonathan Leffler
A: 
SELECT
      M.* ,
      P.Name AS PersonName
FROM 
      Memberships AS m
INNER  JOIN 
      People AS P ON P.PersonID = M.PersonID
WHERE
      M.GroupID = 32
ORDER BY 
      PersonName
p.campbell