Repository navigation
Open
Labels
type: bugDEPRECATED: replace with the "bug" issue type
Description
Issue Description
What are you doing?
I'm trying to run the queries shown here adding the limit parameter on the top level.
I've created a small Codesandbox using the examples on the documentation and adding the limit parameter. The resulting query can be easily seen in the sandbox console.
Here is the query anyway:
User.findAll({
where: {
"$Instruments.id$": { [Sequelize.Op.is]: null }
},
include: {
model: Tool,
as: "Instruments"
},
limit: 2
}).catch((err) => {});What do you expect to happen?
SELECT `user`.*,
`Instruments`.`id` AS `Instruments.id`,
`Instruments`.`name` AS `Instruments.name`,
`Instruments`.`size` AS `Instruments.size`,
`Instruments`.`userId` AS `Instruments.userId`
FROM (
SELECT `user`.`id`,
`user`.`name`
FROM `users` AS `user`
) AS `user`
LEFT OUTER JOIN `tools` AS `Instruments` ON `user`.`id` = `Instruments`.`userId`
WHERE `Instruments`.`id` IS NULL
LIMIT 2What is actually happening?
SELECT `user`.*,
`Instruments`.`id` AS `Instruments.id`,
`Instruments`.`name` AS `Instruments.name`,
`Instruments`.`size` AS `Instruments.size`,
`Instruments`.`userId` AS `Instruments.userId`
FROM (
SELECT `user`.`id`,
`user`.`name`
FROM `users` AS `user`
WHERE `Instruments`.`id` IS NULL
LIMIT 2
) AS `user`
LEFT OUTER JOIN `tools` AS `Instruments` ON `user`.`id` = `Instruments`.`userId`Additional context
I believe the queries and the code explain themselves. What I'm trying to achieve is that exact query:
- Be able to do a LEFT OUTER
- Filter it by the missing matches (ie "id" is NULL)
- Limit the query.
If there is any other way to manage to obtain the query that I expect feel free to suggest it !
Environment
- Sequelize version: 6.4.0
- Node.js version: 10.22.0
- Operating System: macOS / Codesandbox is running a regular linux
Issue Template Checklist
How does this problem relate to dialects?
- I think this problem happens regardless of the dialect.
- I think this problem happens only for the following dialect(s):
- I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX
Would you be willing to resolve this issue by submitting a Pull Request?
- Yes, I have the time and I know how to start.
- Yes, I have the time but I don't know how to start, I would need guidance.
- No, I don't have the time, although I believe I could do it if I had the time...
- No, I don't have the time and I wouldn't even know how to start.
Regards
Reacted by Rafat Alhawash, Dimas Paiva, Ayush Shukla, Hassan Rabbi, Abhishek Burkule, LethaK Maas, Hayk Baghdasaryan, Alyx, Brad Kellogg, hnlichong and 13 more
Metadata
Metadata
Assignees
Labels
type: bugDEPRECATED: replace with the "bug" issue type
Type
Projects
- StatusShow more project fieldsNo status
Activity
github-actions commentedon Oct 27, 2021
MCD-50 commentedon Nov 5, 2021
Are there any updated on this?
bernardmma commentedon Nov 8, 2021
I just encountered this as well. Any ideas?
abhiburk commentedon Jan 18, 2022
When using limit and offset Unknown column in ............ where clause
ephys commentedon Jan 19, 2022
Adding
limitturns the query into a subQuery to ensurelimitonly impacts how many users are returned.Adding$references$ to joined tables should still function.
subQuery: falsecould solve your issue, with a caveat, but this is indeed a bug as even when using a subQuery,ephys commentedon Mar 18, 2022
6 remaining items
carsonweinand commentedon Mar 28, 2022
FYI for my specific use case I need to apply filter criteria across multiple associated models --> for example, check if price falls within a certain range on table abc OR table xyz.
This is why I am using the$association.reference$ syntax because I don't know how to perform the action I just mentioned with using include: [{model: Model}, where: {}]
Taqiarzoo commentedon Mar 29, 2022
.
`order.findAll({
})`
this will return all data but only single record from has_many relations
ephys commentedon Mar 29, 2022
@carsonweinand Your use case is the exact one that would really benefit from supporting this syntax in subQueries. That unfortunately means that right now your only option is to write a raw query.
If you manage to come up with one, don't hesitate to share its details. It would help us resolve this issue
carsonweinand commentedon Mar 29, 2022
@ephys I have one other issue... I am trying to get the count of associated bids and offers but those added attributes don't appear in the output unless I include "raw: true" (but raw: true adds extra results and is incorrect for my use case). My query is below. Do you know why "BidCount" and "OfferCount" don't appear as attributes?
const listingResultsQuery = {
where: listingFilters,
// limit: 25, // when adding a limit it throws error: "missing FROM-clause entry for 'table'"
distinct: true, // used for total count
offset: parseInt(query.offset[0]),
order: sortByQuery(query.sortby ? query.sortby[0] : null),
attributes: [
"id",
"title",
"createdAt",
[
Sequelize.literal(
"(SELECT COUNT() FROM Offer WHERE Offer.listingId = Listing.id)"
),
"OfferCount",
],
[
Sequelize.literal(
"(SELECT COUNT() FROM Bid WHERE Bid.listingId = Listing.id)"
),
"BidCount",
],
],
};
const listingResults = await Models.Listings.findAndCountAll(
listingResultsQuery
);
sreeenivasyadav commentedon Apr 19, 2022
ephys commentedon May 17, 2022
I think I figured out a way to solve this
To sum things up:
The issue
When using
limitandincludein the same query, the expected behavior is that eachlimitonly applies to the model it's added to. The following query:Should return up to two users, each with up to 10 projects.
Right now, Sequelize wraps
Userin a subQuery to make surelimit: 2only applies toUser, notprojects. Which results in (roughly) this:This query breaks down if we try to filter using the association:
results in
First solution (fast)
if the check being done is 'the association does not exist', we don't need to use a subQuery. We should revert back to a regular query for this scenario.
The generated SQL for that query should be:
More general solution (slow)
By using
PARTITION BY, we can build a query that is capable of filtering using associations.Caveats:
limitat the top level. Still need to determine how alimitcan be set for each include.TO DO
limiton each include.subQueryandduplicatingoptions, replace them withqueryStyle: 'simple' | 'subQuery' | 'partitionned'nikkorfed commentedon May 24, 2022
Hi everyone! It seems that there's another way of building a query that is capable of filtering by associations (without partitions).
Using OP's example, for getting 5 users with the instrument's size
largethe SQL-query would be like:The main idea here is that there is a subquery, which is executed with desired
WHERE,LIMITandJOINclauses, but withDISTINCT 'id'also. This produces the list of IDs that satisfies our query (users filtered by joined instruments' size) and the number of IDs in that list is limited to 5.This array of IDs is then used in
WHEREclause for the main query. It retrieves all the users with these IDs and joins required associations to them, sets some order, etc. In the end, we just receive specified number of users filtered by some nested attribute.So the combination of
DISTINCT 'id'andLIMITin a subquery behaves like imaginaryLIMIT ON (id) 5, which says "limit the number of records to keep only 5 unique IDs (instead of rows)".Hope this'll help with resolving the issue. Please, let me know if missed something.
nikkorfed commentedon May 25, 2022
In addition to the above, to limit the number of associations for each include (@ephys's question) ,
JOINin the main query needs a few adjustments. Instead of regularLEFT OUTER JOIN tools AS instruments ON user.id = instruments.userIdthere should be:This
JOINbasically divides associated tools into partitions (for each user), numerates them inrowcolumn and then joins only the ones that are numerated up to 3. As a result, we receive up to 3 tools for each user.verstoff commentedon Sep 6, 2022
Ok, guys, here is some proof-of-concept workaround inspired by @nikkorfed idea.
sdesbiens commentedon Jan 12, 2024
I'm having this issue as well, but I'm wondering if the general SQL structure that's being generated today couldn't be preserved. In my particular example it seems like if the association appears in the main where clause with the
$association.field$sort of style, then the table for that association in the SQL could also be duplicated within the limit subquery from:To something like:
Adding DISTINCT to the Sub query which limits the results to only the fields of the model that's being queried on so you can join other associations that appear in the main WHERE clause without affecting the rows, and then you add the WHERE clause to the outer most part of the query again to filter on those aspects when joining to that table again for the final results.
I was working with Postgres in my example, and had an ORDER BY part, which also requires some care when adding the DISTINCT to the subquery since I specifically added COLLATE "C" to the Sequelize query order which caused me to have to add that expression to the SELECT list of the subquery.
Would that not work?
kurokeita commentedon Nov 29, 2024
Hi, is there any update on this? I'm encountering this issue at the moment with complex top level clauses. Querying with limit does not get all the associations. What I'm doing at the moment is query with complex conditions first to get the ids then do another query
where id in (*)to get the full data.caseyt commentedon Jan 10, 2025
caseyt commentedon Jan 10, 2025