简体   繁体   中英

CodeIgniter db select returns different result than SQL query

I wanted to use the CI Active Record methods to perform this query, but it gives me different results than if I execute the query in plain SQL. This is the query:

SELECT B.id as id
FROM default_log_workout A, default_log_workout B
WHERE A.id=$id AND B.completed < A.completed AND A.workout_id=B.workout_id
ORDER BY B.completed desc
LIMIT 1

CodeIgniter:

$this->db->select("B.id as id");
$this->db->from("log_workout A, log_workout B");
$this->db->where(array("A.id" => $id, "B.completed < A.completed", "A.workout_id=B.workout_id"));
$this->db->order_by("B.completed desc");
$this->db->limit(1);
$res = $this->db->get();

The query should return the next older row based on a given "id". The plain SQL works, the CI calls end up returning the OLDEST row, not the next oldest. I figure it's just a syntax error in my CI calls... but I can't figure it out. I've since moved on to solve the problem with $this->db->query("the SQL") but this is still bugging me.

Anyone know why the CI version doesn't work?

ORDER BY子句应具有两个参数:

$this->db->order_by('B.completed', 'DESC');

I'm not sure if Active Record will parse your comma separated table string in your from() clause. I suggest rewriting it in an ANSI standard from ... join ... on syntax.

$this->db->select("B.id as id");
$this->db->from("log_workout A");
$this->db->join("log_workout B","A.workout_id = B.workout_id AND B.completed < A.completed");
$this->db->where("A.id" => $id);
$this->db->order_by("B.completed", "desc");
$this->db->limit(1);
$res = $this->db->get();

And, as Yan pointed out, the order by should have two parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM