SQL order by a column from another table

断了今生、忘了曾经 提交于 2019-12-18 14:14:07

问题


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?


回答1:


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



回答2:


SELECT *
FROM Membership AS m
     JOIN People as p ON p.personID = m.personID
WHERE m.groupID = 32
ORDER BY p.name



回答3:


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


来源:https://stackoverflow.com/questions/1805600/sql-order-by-a-column-from-another-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!