2017-07-07 53 views
2

我使用sequelize來計算設備在過去24小時內收到的消息數。爲什麼postgres(帶sequelize)如果沒有值會計數1?

Sequelize將要執行下面的請求(I附接在端sequelize代碼)

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"; 

其返回

id count 
24 25790 
163 1 
95 1 

值用於ID 24是正確的,但是其它的值應該是0.

然後我手動執行這個SQL查詢

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; 

它給了我預期的結果。

我無法看到兩個查詢之間的區別。有人知道爲什麼第二個工作?


的sequelize請求是採用以下

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

的SQL具有圍繞records.id單引號,所以SQL計數字符串值(這是從未NULL)。你想要:

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

我不知道如何表達這個在續集中,但問題是單引號。

+0

非常感謝! – ThomasThiebaud

+0

我需要在我的續集中使用'this.database.col('records','id')'使其工作。我會盡快接受答案。 – ThomasThiebaud

相關問題