question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to Count/Select in subqueries?

See original GitHub issue

What 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:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
Paxacommented, Jul 19, 2018

You can also do it with subquery:

A.findAll({
  attributes: { include: [
    [
      sequelize.literal('SELECT COUNT(*) FROM B, C WHERE B.id = C.bId AND B.aId = "A".id'),
      'attr3'
    ],
  ]}
});
0reactions
recoiladamcommented, Aug 22, 2021

You can also do it with subquery:

A.findAll({
  attributes: { include: [
    [
      sequelize.literal('SELECT COUNT(*) FROM B, C WHERE B.id = C.bId AND B.aId = "A".id'),
      'attr3'
    ],
  ]}
});

This no longer seems to work.

models.organizations.findAll({
  attributes: {
    include: [
      [
        sequelize.literal('SELECT COUNT(*) FROM farms'), 'totalFarms'
      ]
    ]
  }
}).then(data => {
  resolve(data)
}).catch(error => {
  reject(new Error(error))
})

Builds an invalid query:

'SELECT `id`, `uuid`, `salesUserId`, `name`, `isActive`, `isDeleted`, `createdAt`, `updatedAt`, SELECT COUNT(*) FROM farms AS `totalFarms` FROM `organizations` AS `organizations`;

Error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(*) FROM farms AS `totalFarms` FROM `organizations` AS `organization' at line 1
Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found