How to Count/Select in subqueries?
See original GitHub issueWhat are you doing?
return A.findAll({
attributes: ['id', 'attr1', 'attr2', [sequelize.fn('COUNT', '*'), 'attr3']],
include: [{
model: B,
attributes: [ ],
include: [{
model: C,
attributes: [ ]
}]
}]
});
What do you expect to happen?
For this example, consider that there are:
- 2 records of A
- 5 records of B
- 6 records of C
SQL query:
SELECT A.`attr1`, A.`attr2`,
(SELECT COUNT(*) FROM B, C
WHERE B.id = C.bId AND B.aId = A.id) AS `attr3`
FROM A;
JSON example (con):
[
{
"id": 1,
"attr1": "whatever",
"attr2": "whatever",
"attr3": 4
},
{
"id": 2,
"attr1": "whatever",
"attr2": "whatever",
"attr3": 2
}
]
What is actually happening?
SQL query:
SELECT A.attr1, A.attr2, COUNT('*') AS attr3 FROM A
LEFT OUTER JOIN B ON A.id = B.aId
LEFT OUTER JOIN C ON B.id = C.bId;
JSON example:
[
{
"id": 2,
"attr1": "whatever",
"attr2": "whatever",
"attr3": 6
}
]
Dialect: mysql / postgres / sqlite / mssql / any Dialect version: sqlite Database version: sqlite3.1.13 Sequelize version: sequelize 4.28.1 and sequelize-cli 3.2.0 Tested with latest release: Yes
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:8 (1 by maintainers)
Top Results From Across the Web
SQL subquery with COUNT help - Stack Overflow
SELECT *, (SELECT Count(*) FROM eventsTable WHERE columnName = 'Business') as RowCount FROM eventsTable WHERE columnName = 'Business'.
Read more >Counting rows from a subquery - mysql - DBA Stack Exchange
To answer your immediate question, how to count rows of a subquery, the syntax is as follows: SELECT COUNT(*) FROM (subquery) AS some_name;....
Read more >Example: Using SELECT COUNT(*) in a Correlated Subquery
Select the names of the publishers whose book count values in the library match the actual count of books. SELECT pubname, bookcount FROM ......
Read more >How do you use subqueries to count distinct in SQL? - Quora
No. If a subquery involves aggregates such as COUNT(*) or GROUP BY - and the aggregates are used as part of the qualification...
Read more >SQL Subquery | Nested query - Dofactory
List all suppliers with the number of products they offer. SELECT CompanyName, ProductCount = (SELECT COUNT(P.id) FROM [Product] P WHERE P.SupplierId ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
You can also do it with subquery:
This no longer seems to work.
Builds an invalid query:
Error: