Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Emulating row_number function. #51

Open
clodoaldofavaro opened this issue Jun 23, 2021 · 0 comments
Open

Emulating row_number function. #51

clodoaldofavaro opened this issue Jun 23, 2021 · 0 comments

Comments

@clodoaldofavaro
Copy link

clodoaldofavaro commented Jun 23, 2021

Hello there, how is it going?

I've run into a interesting puzzle trying to emulate the row_number function.

With raw SQL, I found how to do it in two ways:

select row_number as seqItem

from 

	(select
		`i`.`id`,
		@curRow := @curRow + 1 AS row_number
	from
		`orderitem` as `i`,
		(select @curRow := 0) as `r`
	where
		`i`.`idCompany` = '123'
		and `i`.`idOrder` = '456'
	) sub	

where sub.id = '789'; 

or

select row_number as seqItem

from 

	(select
		`i`.`id`,
		@curRow := @curRow + 1 AS row_number
	from
		`orderitem` as `i`
	inner join
		(select @curRow := 0) as `r`
	where
		`i`.`idCompany` = '123'
		and `i`.`idOrder` = '456'
	) sub	

where sub.id = '789'; 

I've tried doing the following

$subSelect = $qb->table(['orderitem' => 'i', '(select @curRow := 0)' => 'r'])->select('i.id', $qb->raw('@curRow := @curRow + 1 AS row_number'))
		  ->where('i.idCompany', $idCompany)
		  ->where('i.idOrder', $idOrder);

$qb = $qb->table(['sub' => $subSelect])->select(['row_number' => 'seqItem'])->where('sub.id', $idOrderItem);

which resulted in the query string

select
	`row_number` as `seqItem`
from
	(
	select
		`i`.`id`,
		@curRow := @curRow + 1 AS row_number
	from
		`orderitem` as `i`,
		`(select @curRow := 0)` as `r`
	where
		`i`.`idCompany` = '123'
		and `i`.`idOrder` = 456) as `sub`
where
	`sub`.`id` = 789;

and it resulted in a error because of the backticks in

`(select @curRow := 0)`

Is this not supported, or I'm just missing something?

Best regards!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant