Alb Alb
Alb Alb

Reputation: 9

Order by issue in msql query gives syntax error

I have this query here:

$query_pag_data = "SELECT 
matching.date,
matching.points,
matching.time,
matching.location,
matching.epos_id,
matching.time_added,
rbpos_epos.epos_id,
rbpos_epos.location
FROM
matching
LEFT JOIN
rbpos_epos ON matching.epos_id = rbpos_epos.epos_id
WHERE
matching.user_id = ".$id_user." LIMIT $start, $per_page ORDER BY matching.time_added DESC";

I get an error in the ORDER BY part, what is wrong, where should i put it? ...

Upvotes: 0

Views: 93

Answers (2)

Erik Schierboom
Erik Schierboom

Reputation: 16646

You have swapped the order of the ORDER BY and LIMIT clauses. The ORDER BY clause comes first, then the LIMIT clause. This should work:

$query_pag_data = "SELECT 
matching.date,
matching.points,
matching.time,
matching.location,
matching.epos_id,
matching.time_added,
rbpos_epos.epos_id,
rbpos_epos.location
FROM
matching
LEFT JOIN
rbpos_epos ON matching.epos_id = rbpos_epos.epos_id
WHERE
matching.user_id = ".$id_user." ORDER BY matching.time_added DESC LIMIT ".$start.", ".$per_page;

Upvotes: 1

lvarayut
lvarayut

Reputation: 15279

The limit is always applied at the end of result gathering, therefore after order by.

Given all your clauses, the order of processing will be

  • FROM
  • WHERE
  • SELECT
  • ORDER BY
  • LIMIT

So you will get the closest record <= publishedOn matching all the conditions in the WHERE clause.

@credit : RichardTheKiwi

Upvotes: 0

Related Questions