带有子查询GROUP BY和MAX的MySQL查询

hlswsv35  于 2023-02-07  发布在  Mysql
关注(0)|答案(1)|浏览(144)

(更新了问题,以更清楚地说明预期结果)

    • 表格**

主表

左联接表

查询

SELECT m.id           AS id,
       m.receiverId   AS receiverId,
       m.creationDate AS creationDate,
       m.status       AS status,
       m.tokens       AS tokens,
       mm.carrier     AS carrier,
       mm.fromNumber  AS fromNumber,
       mm.keyword     AS keyword,
       mm.ref         AS ref,
       mm.message     AS message
FROM ctb_smsMessenger AS m
         LEFT JOIN ctb_smsMessengerMessage AS mm ON m.id = mm.smsMessengerId
WHERE m.status IN ("new")
    • 结果**

    • 预期结果**

使用IDS2、11、14和19从两个表中获取具有正确列的记录。

    • 查询到目前为止**
SELECT *
FROM (SELECT m.id      AS id,
             m.receiverId   AS receiverId,
             m.creationDate AS creationDate,
             m.status       AS status,
             m.tokens       AS tokens,
             mm.carrier     AS carrier,
             mm.fromNumber  AS fromNumber,
             mm.toNumber    AS toNumber,
             mm.keyword     AS keyword,
             mm.ref         AS ref,
             mm.message     AS message
      FROM ctb_smsMessenger AS m
               LEFT JOIN ctb_smsMessengerMessage AS mm ON m.id = mm.smsMessengerId
      WHERE m.status IN ("new")
      GROUP BY m.receiverId, mm.fromNumber) as m
ORDER BY m.id DESC
LIMIT 0, 20
    • 迄今为止的结果**

    • 问题**

只有ID列显示了正确的数据(ID)。其他列的数据不匹配。

    • 期待什么**

每个receiverID可以有不同的多个numberFrom编号。
根据receiverId和numberFrom获取包含最后插入的记录的所有记录。(IDS2、11、14和19)

oxosxuxt

oxosxuxt1#

解决方案是获取ID值最大的所有记录,按m.receiverId和mm.fromNumber分组,并在WHERE IN子句中使用IN。

SELECT m.id           AS id,
       m.receiverId   AS receiverId,
       m.creationDate AS creationDate,
       m.status       AS status,
       m.tokens       AS tokens,
       mm.carrier     AS carrier,
       mm.fromNumber  AS fromNumber,
       mm.toNumber    AS toNumber,
       mm.keyword     AS keyword,
       mm.ref         AS ref,
       mm.message     AS message
FROM ctb_smsMessenger AS m
         LEFT JOIN ctb_smsMessengerMessage AS mm ON m.id = mm.smsMessengerId
WHERE m.status IN ("new")
  AND m.id IN (SELECT MAX(m.id) AS id
               FROM ctb_smsMessenger AS m
                        LEFT JOIN ctb_smsMessengerMessage AS mm ON m.id = mm.smsMessengerId
               WHERE m.status IN ("new")
               GROUP BY m.receiverId, mm.fromNumber)
GROUP BY m.receiverId, mm.fromNumber
ORDER BY m.id ASC

相关问题