i have 2 tables, one for users (recruiters) and the other for CV
CREATE TABLE users (
id int primary,
email string,
company string
)
CREATE TABLE cv (
id int primary,
title string,
user_id int,
created_date datetime
)
The user can post many CV .
So what i want is to select the last CV from each user ordred by created_date than the next cv and so on...
the result would be like this:
the list of CV is ordred by created_date DESC
what i want is one entry (the last) for each user, than the next entry for each user:
last Entry for user 1
last entry for user 2
last entry for user 3
last entry for user 4
....and so on...than
the entry before the last (because entries are ordred by date desc) for user 1
the entry before the last for user 2
the entry before the last for user 3
...and so on...
i have found this solution by it doesn't work
SELECT IF(@prev != a.`company_name`, @rownum:=1, @rownum:=@rownum+1)
as rownumber, @prev:=a.`company_name`, a.* FROM
(SELECT `cv`.`id` AS `id` , `cv`.`company_name` FROM `cv` ,
(SELECT @rownum := 0, @prev:='') sq ORDER BY `created_date` DESC) a order by rownumber
The correct version for your problem is:
select cv.*
from (select cv.*,
(@rn := if(@c = company_name, @rn + 1,
if(@c := company_name, 1, 1)
)
) as rn
from cv cross join
(select @c := '', @rn := 0) vars
order by company_name, created_date desc
) cv
order by rn, user_id;
You want to put all the variable assignments in a single expression, because MySQL does not guarantee the order of evaluation of expressions in a select
. You can join in additional information from other tables.
i found this solution, and it seems to work:
SELECT IF(@prev != a.`user_id`, @rownum:=1, @rownum:=@rownum+1) as rownumber,
@prev:=a.`user_id`, a.* FROM (SELECT `cv`.`id` AS `id` , `cv`.`company_name` ,
cv.created_date, `cv`.`user_sid` FROM `cv` , (SELECT @rownum := 0, @prev:='') sq
{WHERE CLAUSE} ORDER BY `cv`.`user_id` ASC, `cv`.`created_date` DESC) a order by rownumber,
created_date desc;
if you have a where clause you can put it in the {WHERE CLAUSE}
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.