从INNER JOIN 3表中获取每张表中LASTEST RECORD的值

时间:2017-07-25 03:16:12

标签: mysql sql sql-order-by inner-join

我从一些表中获取价值时遇到问题。你可以看到下面的图片,我想要用红色阻挡我的行。 enter image description here

我尝试使用下面的代码

SELECT p.id, 
       p.email, 
       p.name, 
       p.lastname, 
       p.gender, 
       ex.startwork, 
       ex.endwork, 
       e.degree, 
       e.majority, 
       j.division 
FROM   job_jobseeker AS p 
       INNER JOIN job_experience AS ex 
               ON p.email = (SELECT ex.email 
                             FROM   job_experience 
                             ORDER  BY ex.id DESC 
                             LIMIT  1) 
       INNER JOIN job_education AS e 
               ON p.email = (SELECT e.email 
                             FROM   job_education 
                             ORDER  BY ex.id DESC 
                             LIMIT  1) 
       INNER JOIN job_applying AS j 
               ON p.email = (SELECT j.email 
                             FROM   job_applying 
                             ORDER  BY ex.id DESC 
                             LIMIT  1) 

1 个答案:

答案 0 :(得分:1)

您需要correlated sub-queries

查找所有三个表中每个id的最新email

SELECT startwork, 
       endwork, 
       email 
FROM   job_experience a 
WHERE  a.id = (SELECT Max(b.id) 
               FROM   job_experience b 
               WHERE  a.email = b.email) 

上述查询将在job_experience表中找到每封电子邮件的最新ID。对其他两个表执行相同操作,然后将结果与job_jobseeker表连接以获得结果。

SELECT p.id, 
       p.email, 
       p.name, 
       p.lastname, 
       p.gender, 
       ex.startwork, 
       ex.endwork, 
       e.degree, 
       e.majority, 
       j.division 
FROM   job_jobseeker AS p 
       INNER JOIN (SELECT startwork, 
                          endwork, 
                          email 
                   FROM   job_experience a 
                   WHERE  a.id = (SELECT Max(b.id) FROM job_experience b 
                                  WHERE  a.email = b.email)) AS ex 
               ON p.email = ex.email 
       INNER JOIN (SELECT email,  //Just called column without initialize
                          degree, 
                          majority 
                   FROM   job_education a 
                   WHERE  a.id = (SELECT Max(b.id) FROM job_education b 
                                  WHERE  a.email = b.email)) AS e 
               ON p.email = e.email 
       INNER JOIN (SELECT email, //Just called column without initialize
                          division 
                   FROM   job_applying a 
                   WHERE  a.id = (SELECT Max(b.id) FROM job_applying b 
                                  WHERE  a.email = b.email)) AS j 
               ON p.email = j.email