Josh Mountain
Josh Mountain

Reputation: 1950

Sorting using ORDER BY on a JOIN query

I am trying to use ORDER BY to sort a query, but it is claiming there is a syntax error. My query looks like this before trying to sort:

SELECT u.*, s.*
FROM bands u
inner join statuses s on u.status_id = s.id
WHERE u.status_id = 1
LIMIT {$startpoint}, {$limit}

I have tried adding ORDER BY like this but is doesn't seem to be correct:

SELECT u.*, s.*
FROM bands u
inner join statuses s on u.status_id = s.id
WHERE u.status_id = 1
LIMIT {$startpoint}, {$limit} ORDER BY u.status_id

How can I use ORDER BY properly inside this query?

Upvotes: 0

Views: 74

Answers (2)

andrewsi
andrewsi

Reputation: 10732

You're amost there - you just have the ORDER and the LIMIT the wrong way round:

SELECT 
    u.*, s.* 
FROM 
    bands u inner join statuses s on u.status_id = s.id 
WHERE 
    u.status_id = 1 
ORDER BY u.status_id
LIMIT {$startpoint}, {$limit} 

Upvotes: 1

John Woo
John Woo

Reputation: 263693

ORDER BY clause comes before LIMIT

SELECT u.*, s.*
FROM bands u
inner join statuses s on u.status_id = s.id
WHERE u.status_id = 1
ORDER BY u.status_id
LIMIT {$startpoint}, {$limit} 

Upvotes: 1

Related Questions