2

I'm using sequelize to count the number of messages that a device received during the last 24 hours.

Sequelize is going to execute the following request (I attached sequelize code at the end)

SELECT "device"."id", COUNT('records.id') AS "count"
FROM "device" AS "device"
  LEFT OUTER JOIN "record" AS "records" ON "device"."id" = "records"."deviceId" AND "records"."date" > '2017-07-06 08:09:40.468 +00:00'
WHERE "device"."typeId" = '2'
GROUP BY "device"."id";

which return

id   count
24  25790
163 1
95  1

the value for the id 24 is correct, but the other values should be 0.

I then manually execute this SQL query

SELECT device.id, COUNT(record.id) AS count
FROM device AS device
  LEFT OUTER JOIN record ON device.id = record."deviceId" AND record.date > '2017-07-06 08:09:40.468 +00:00'
WHERE device."typeId" = '2'
GROUP BY device.id;

which gives me the expected result.

I'm not able to see the difference between the two queries. Does someone know why the second is working?


The sequelize request is the following

const devices = await this.database.model('device').findAll({
  where: {
    typeId: req.params.id,
  },
  attributes: {
    include: [
      'id',
      [this.database.fn('COUNT', 'records.id'), 'count'],
    ],
  },
  include: [{
    model: this.database.model('record'),
    where: {
      date: {
        $gt: oneDayAgo,
      },
    },
    attributes: [],
    required: false,
  }],
  group: ['device.id'],
})

2 Answers 2

2

The SQL has single quotes around records.id, so SQL is counting a string value (which is never NULL). You want:

SELECT "device"."id", COUNT(records.id) AS "count"

I don't know how to express this in sequelize, but the problem is the single quotes.

Sign up to request clarification or add additional context in comments.

1 Comment

I need to use this.database.col('records', 'id') in my sequelize to make it work. I will accept the answer as soon as I can.
0

Easiest way to do it in sequelize would be by passing 'records.id' to this.database.col(). By that Sequelize shouldn't quote identifier.

Actually you should use this function with each and every column you pass to Sequelize. By doing that Sequelize can generate more accurate queries.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.