Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL order by a column from another table

Tags:

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?

like image 346
Florent2 Avatar asked Nov 26 '09 20:11

Florent2


People also ask

Can we use ORDER BY for 2 columns?

After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name ). You can modify the sorting order (ascending or descending) separately for each column.

Can we use ORDER BY in SQL?

The SQL ORDER BY KeywordThe ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you ORDER BY a column?

Select a cell in the column you want to sort. On the Data tab, in the Sort & Filter group, click Sort. In the Sort dialog box, under Column, in the Sort by or Then by box, select the column that you want to sort by a custom list.

Does ORDER BY column need to be in SELECT?

The column-Name that you specify in the ORDER BY clause does not need to be the SELECT list.


2 Answers

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 
like image 71
Donnie Avatar answered Sep 20 '22 11:09

Donnie


SELECT * FROM Membership AS m      JOIN People as p ON p.personID = m.personID WHERE m.groupID = 32 ORDER BY p.name 
like image 43
Damir Sudarevic Avatar answered Sep 22 '22 11:09

Damir Sudarevic