我试图获得具有相同的medicine_id和唯一的insurance_id和最后插入行的数据。把分组和顺序,但其中得到的随机数据不是最后插入。我尝试了这个代码,但没有得到最后插入的数据
SELECT
`m1`.`*`
FROM
(
`pricings` `m1`
LEFT JOIN `pricings` `m2` ON
(
(
(
`m1`.`medicine_id` = `m2`.`medicine_id`
)
)
)
)
WHERE m1.medicine_id = 2
group BY m1.insurance_id DESC
ORDER BY m1.created_at;
这里是总行。这是一个完整的表
<表类>id medicine_id insurance_id created_at tbody><<tr>4311 2 1 2021-04-12 16:05:07 4766 2 1 2022-01-15 11:56:06 4767 2 38 2021-05-12 08:17:11 7177 2 38 2022-03-30 10:14:11 4313 2 39 2021-04-12 16:05:46 4768 2 39 2021-05-12 08:17:30 1356 2 40 2020-11-02 11:25:43 3764 2 40 2021-03-08 15:42:16 4769 2 40 2021-05-12 08:17:44 表类>
MySQLx:使用子查询来查找每个组的最大created_at值,然后在源表上连接该值以确定它来自哪一行。
SELECT
p.`*`
FROM
`pricings` p
INNER JOIN
(
SELECT
`medicine_id`,
`insurance_id`,
MAX(created_at) AS `created_at`
FROM
`pricings`
GROUP BY
`medicine_id`,
`insurance_id`
)
p_max
ON p.`medicine_id` = p_max.`medicine_id`
AND p.`insurance_id` = p_max.`insurance_id`
AND p.`created_at` = p_max.`created_at`
WHERE
p.`medicine_id` = 2
ORDER BY
p.`created_at`;
MySQL 8:使用ROW_NUMBER()
枚举每个组,然后从每个组中选择第一行
SELECT
p.`*`
FROM
`pricings` p
FROM
(
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY `medicine_id`,
`insurance_id`
ORDER BY `created_at` DESC
)
AS `row_id`
FROM
`pricings`
)
p
WHERE
p.`medicine_id` = 2
AND p.`row_id` = 1
ORDER BY
p.`created_at`;
将其添加为答案。我没有测试过它,只是修复格式与你正在使用的任何版本的数据库工作,让我知道结果。
SELECT m1.id , m1.Insurance_id , m1.medicine_id , max(m1,created_at)
FROM (
`pricings` `m1` LEFT JOIN `pricings` `m2` ON `m1`.`medicine_id` = `m2`.`medicine_id`
)
WHERE m1.medicine_id = 2 and m1.insurance_id in (1,39,40,38)
GROUP BY m1.insurance_id DESC
ORDER BY m1.created_at;
编辑。我还删除了6个额外的括号,我不知道它们有什么用