SQL 按另一表中的列排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1805600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 04:34:26  来源:igfitidea点击:

SQL order by a column from another table

sqlsql-order-by

提问by Florent2

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).

我有 3 个表:人员、组和成员资格。Memberships 是人与组之间的连接表,有 3 列:personId、groupId 和 description(文本)。

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)

我想根据 groupId 从成员资格表中选择条目,但按与找到的成员资格关联的人员姓名对结果进行排序(名称是人员表的一列)

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

Is it possible to achieve this in one single query?

是否可以在一个查询中实现这一目标?

回答by Donnie

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

加入 people 表,然后按所需字段排序。

SELECT
  m.* 
FROM 
  "memberships" AS m
  JOIN "people" AS p on p.personid = m.personID
WHERE
  m.groupId = 32
ORDER BY 
  p.name

回答by Damir Sudarevic

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

回答by p.campbell

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