SELECT a1.id, a1.name, a1.category_id as categoryId, a2.name as categoryName, a3.id as mgId, a4.id as mid, a4.maintenance_date as maintenanceDate FROM t_goods a1 LEFT JOIN t_goods_category a2 ON a2.id = a1.category_id LEFT JOIN t_maintenance_register_goods a3 ON a3.goods_id = a1.id LEFT JOIN t_maintenance_register a4 ON a4.id = a3.register_id WHERE a1.is_delete = 0 AND a1.is_scrap = 0 这个sql语句会出现重复,重复的记录a4.maintenance_date属性会不同,只保留最早的a4.maintenance_date 帮我改一下sql
时间: 2024-03-15 22:47:00 浏览: 66
你可以使用以下 SQL 语句来查询多个表中除了时间都重复的记录,并保留时间最早的那条:
```
SELECT a1.id, a1.name, a1.category_id AS categoryId, a2.name AS categoryName, a3.id AS mgId, a4.id AS mid, a4.maintenance_date AS maintenanceDate
FROM t_goods a1
LEFT JOIN t_goods_category a2 ON a2.id = a1.category_id
LEFT JOIN t_maintenance_register_goods a3 ON a3.goods_id = a1.id
LEFT JOIN (
SELECT t_maintenance_register_goods.register_id, MIN(t_maintenance_register.maintenance_date) AS maintenance_date
FROM t_maintenance_register_goods
LEFT JOIN t_maintenance_register ON t_maintenance_register.id = t_maintenance_register_goods.register_id
GROUP BY t_maintenance_register_goods.register_id
) a4 ON a4.register_id = a3.register_id
WHERE a1.is_delete = 0 AND a1.is_scrap = 0
```
这个语句会查询多个表,并且连接列 `category_id`、`goods_id` 和 `register_id`,并保留时间最早的那条记录。你需要根据实际情况修改列名和条件。
阅读全文