Repository navigation
Open
Labels
type: bugDEPRECATED: replace with the "bug" issue type
Description
I'm trying to sum up the total amount for a particular user, using a column in another table. It is similar to this issue which was resolved: #2353
But I tried to apply it, but I get an error:
user
hasMany(models.history)
history
amount: DataTypes.INTEGER,
belongsTo(models.user)
Try query:
models.user.find({where: { id: 1 },
group:['user.id'],
attributes: [[Sequelize.fn('SUM', Sequelize.col('histories.amount')), 'total']],
include: [{model: models.history}]
}).then(function(user) {
console.log(user);
}).catch(function(error) { console.log(error) });
Which will throw the error:
{ name: 'SequelizeDatabaseError',
message: 'column "histories.id" must appear in the GROUP BY clause or be used in an aggregate function',
parent:
{ [error: column "histories.id" must appear in the GROUP BY clause or be used in an aggregate function]
name: 'error',
length: 167,
severity: 'ERROR',
code: '42803',
detail: undefined,
hint: undefined,
position: '59',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_agg.c',
line: '911',
routine: 'check_ungrouped_columns_walker',
sql: 'SELECT "user"."id", SUM("histories"."amount") AS "total", "histories"."id" AS "histories.id", "histories"."amount" AS "histories.amount", "histories"."other" AS "histories.other", "histories"."createdAt" AS "histories.createdAt", "histories"."updatedAt" AS "histories.updatedAt", "histories"."userId" AS "histories.userId", "histories"."itemId" AS "histories.itemId" FROM "users" AS "user" LEFT OUTER JOIN "histories" AS "histories" ON "user"."id" = "histories"."userId" WHERE "user"."id" = 1 GROUP BY "user"."id";' },
original:
The sql that is generated is:
Executing (default): CREATE TABLE IF NOT EXISTS "users" ("id" SERIAL , "name" VARCHAR(255), PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' and t.relname = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "items" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "items" ("id" SERIAL , "name" VARCHAR(255), PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' and t.relname = 'items' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "histories" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "histories" ("id" SERIAL , "amount" INTEGER, "other" VARCHAR(255), "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "userId" INTEGER REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE CASCADE, "itemId" INTEGER REFERENCES "items" ("id") ON DELETE SET NULL ON UPDATE CASCADE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' and t.relname = 'histories' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "users" ("id","name") VALUES (DEFAULT,'bob') RETURNING *;
Executing (default): INSERT INTO "items" ("id","name") VALUES (DEFAULT,'itme') RETURNING *;
Executing (default): INSERT INTO "histories" ("id","amount","userId","itemId","updatedAt","createdAt") VALUES (DEFAULT,5,1,1,'2015-03-03 03:38:18.110 +00:00','2015-03-03 03:38:18.110 +00:00') RETURNING *;
Executing (default): INSERT INTO "histories" ("id","amount","userId","itemId","updatedAt","createdAt") VALUES (DEFAULT,10,1,1,'2015-03-03 03:38:18.114 +00:00','2015-03-03 03:38:18.114 +00:00') RETURNING *;
Executing (default): SELECT "user"."id", SUM("histories"."amount") AS "total", "histories"."id" AS "histories.id", "histories"."amount" AS "histories.amount", "histories"."other" AS "histories.other", "histories"."createdAt" AS "histories.createdAt", "histories"."updatedAt" AS "histories.updatedAt", "histories"."userId" AS "histories.userId", "histories"."itemId" AS "histories.itemId" FROM "users" AS "user" LEFT OUTER JOIN "histories" AS "histories" ON "user"."id" = "histories"."userId" WHERE "user"."id" = 1 GROUP BY "user"."id";
I also found a similar bug report (using count instead of sum):
#3009
I think the two might be related. Is there a current workaround?
Using sequelize 2.0.3, postgres dialect
Reacted by Cole Jancsar, Gustavo Silva and Ciro Santilli (三西猴) OurBigBook.com sponsor me: cirosantilli.com/sponsor, opinions my own 2020冠状病毒审查 ,2020郝海东 ,2018新疆改造中心,1989六四事件,1999法轮功 ,2019 996.ICU, 2018包子露宪,2015 709大抓捕,2015巴拿马文件 邓家贵,2017低端人口,2008西藏骚乱<script>alert(1)</script>
Metadata
Metadata
Assignees
Labels
type: bugDEPRECATED: replace with the "bug" issue type
Type
Projects
- StatusShow more project fieldsNo status
Activity
mickhansen commentedon May 20, 2015
Can be fixed with
include.attributes = []on3.0.1ayankelevichionia commentedon Jun 3, 2015
Hi mickhansen,
I'm experiencing this same issue on version 3.1.1, postgres dialect.
I'm not sure were to include the "include.attributes = []" or how to use it.
Can you provide me with an example on how to use this?
mickhansen commentedon Jun 4, 2015
@ayankelevichionia You'd have to show some code for me to show you how to use it, but you simply add
attributes: []to your include options set (include: [{ .. options .. }])ayankelevichionia commentedon Jun 4, 2015
@mickhansen Here's an example of what I'm trying to do:
This is the sql query that gets generated:
As you can see, it is including the Id of inventory_transaction and product. How would I go to exclude them so I don't recieve the error?
Thanks & Regards.
mickhansen commentedon Jun 5, 2015
@ayankelevichionia What version is this?
ayankelevichionia commentedon Jun 5, 2015
@mickhansen According to the package.json, it is version 3.1.1
mickhansen commentedon Jun 6, 2015
@ayankelevichionia What does npm list say? you might have forgotten to npm install
ayankelevichionia commentedon Jun 9, 2015
@mickhansen
npm list says:
mickhansen commentedon Jun 10, 2015
Hmm that's odd.
nadavoosh commentedon May 4, 2016
Is this issue resolved? I'm running into it now.
ieow commentedon Dec 12, 2016
any workaround on this issue?
jorbascrumps commentedon Jan 6, 2017
Having a similar issue with
v3.10.8.rajshrimohanks commentedon Jan 18, 2017
Same here v3.29.0
saudpunjwani101 commentedon Mar 11, 2017
same here even at 4.0 +
41 remaining items
rener172846 commentedon Aug 13, 2019
I think this is the shortest codes:
So only one field -
"reply"."count"is included on the post table.And following is the generated sql from that:
And this sql occurs error -
"column \"reply.id\" must appear in the GROUP BY clause or be used in an aggregate function".So the purpose is just remove
"reply"."id"field from the joined tablepost_comments.On the included model, if
attributesis once specified, theprimary keyshouldn't be added automatically because it will be cause of the group by issue when there is aggregate field.Following sql is what I want as shorten:
Hope is this clear and helpful for your working @papb
papb commentedon Aug 13, 2019
@rener172846 One more thing: you have posted a code snippet that shows the problem but is not entirely self-contained (i.e. I can't just copy-paste it and run it). Can you (or someone else) please provide a SSCCE (also known as MCVE/reprex)?
papb commentedon Oct 10, 2019
@rener172846 @jorbascrumps The reason I'm asking for an SSCCE is that investigating this issue as-is would need extra effort from maintainers (and our time is really short). There is a sequelize-sscce repository to assist with this now. For those hoping for a fix, doing this would greatly help and in theory is something anyone encountering this issue should be able to do. Thanks for understanding! Don't forget to link to this issue in the new issue.
jorbascrumps commentedon Oct 21, 2019
@papb I don't recall why I 👎 your comment. Thank you for taking the initiative in creating that repo and for continuing to investigate this issue.
papb commentedon Oct 21, 2019
@jorbascrumps Ok, thanks 👍
mrdulin commentedon Mar 19, 2020
same issue. I have two tables:
GroupsandEmployeesand the relationship between them is Many-to-Many. So there is a through table namedGroupEmp. I want to group byGroups.groupIdand count the employees for each group. Got error:I had tried
include.attributes: [], it doesn't work.Here is the SSCCE: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/59154486-todo
aristov commentedon Mar 21, 2020
Probably the same issue: #12020
EinfachHans commentedon Feb 13, 2021
Same Issue here...
EinfachHans commentedon Apr 8, 2021
This issue was created 6 years ago. Some did create a SSCCE over one year ago. I get this for nearly every a bit conplex query. When can we get a fix? 😩
arielectron commentedon Sep 5, 2021
Hi.
I was able to solve it using raw option with true value.
marscrusader commentedon Oct 7, 2021
For anybody using
throughor junction tables, here's the solution:Adding
through: { attributes: [] }will ignore the attributes from thethroughtable.Tested for postgres
cirosantilli commentedon Nov 9, 2021
This thread a more precise related report: #5481 my minimal repro: #5481 (comment)
The problem is database specific: SQLite allows columns that are not GROUP BY in the SELECT, which can allow for unpredictable values being selected in the output, but PostgreSQL doesn't and gives the error.