简体   繁体   English

sql select,获取每辆车的最新条目

[英]sql select,get most recent entry for each car

My database (MySql) has 2 tables 我的数据库(MySql)有2个表

Table 1 - contains a record for each car 表1-包含每辆车的记录

cars= id(int), reg(int), type(int) 汽车= id(int),reg(int),type(int)

Table 2 - contains jobs for each car 表2-包含每辆车的工作

jobs = id(int),date(date) 工作= id(int),date(date)

I need a SELECT command which will get me the most recent job for all id's 我需要一个SELECT命令,它将为我提供所有ID的最新工作

Thanks in advance. 提前致谢。

You don't have a shared field, you cant do this. 您没有共享字段,您无法执行此操作。 You need to store the associated car_id with each job, or have a jobs_to_cars table. 您需要将关联的car_id与每个作业一起存储,或者具有一个jobs_to_cars表。

Then you'd use: 那你就用了:

SELECT C.*, J.id, MAX(J.date)
FROM cars C 
INNER JOIN jobs J on J.car_id = C.id
GROUP BY C.id

If job's id IS the same as car's id then change j.car_id to j.id, but then you'd be lacking primary key on Jobs, which i suggest youd start making. 如果Job的ID与汽车的ID相同,则将j.car_id更改为j.id,但是您会缺少Jobs的主键,我建议您开始制作。

You could use something like this 你可以用这样的东西

SELECT c.*, MAX(j.date) date
FROM cars c 
   LEFT JOIN jobs j ON j.id = c.id
GROUP BY c.id
ORDER BY c.id

because you don't have other fields in [jobs]. 因为您在[职位]中没有其他字段。 If a car don't have any jobs, date will be NULL. 如果汽车没有任何工作,则日期将为NULL。

    SELECT *
      FROM cars c
INNER JOIN (SELECT MAX(id) AS j_id
              FROM jobs
          GROUP BY car_id) x ON x.j_id = c.id
  1. You forgot the jobs.car_id field, that specifies which car job belongs to 您忘记了jobs.car_id字段,该字段指定了哪个汽车作业属于
  2. More elegant way will be to create the field car.last_job_id and maintain it with trigger on jobs table. 更优雅的方式是创建领域car.last_job_id并与触发保持它jobs表。

Since your question is not clear, this query also can be an answer: 由于您的问题不清楚,因此该查询也可以作为答案:

    SELECT j.*
      FROM jobs j
INNER JOIN (SELECT MAX(id) id
              FROM jobs
          GROUP BY car_id) x ON x.id = j.id

你可以试试

ORDER BY date DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM