简体   繁体   中英

mysql how to query based on latest relationship data

I have two table

  1. companies
  2. company_relocation_histories

Relationship is Company HAS MANY Relocation History

Sample data table companies

在此处输入图片说明

Sample data table company_relocation_histories

在此处输入图片说明

Sample DB -> https://www.dropbox.com/s/e8uvuc9vvgacz0q/test.sql?dl=0

I want to query all Company that has recently relocate to certain place, for example to FR. Only last location will be counted for.

Expected data is ONLY company id 1 (MIB) will be listed.

Company id 3 (SKD) will be excluded because although they have relocate to FR before, the last relocation is SG.

Here is my take on the SQL query which is not working yet (wrong result). How to solve this? Thanks Stack Overflow!

SELECT * 
FROM   `companies` 
WHERE  EXISTS (SELECT * 
               FROM   `company_relocation_histories` 
               WHERE  `companies`.`id` = 
`company_relocation_histories`.`company_id` 
                      AND `relocation_location` = 'FR' 
                      AND `id` = (SELECT Max(id) 
                                  FROM   `company_relocation_histories` AS `sub` 
                                  WHERE  sub.relocation_location = 
       company_relocation_histories.relocation_location)) 

Check this query. inner query groups reloaction_histories to get the company_id's which has minimum two or more relocations.

select * from companies 
where id in (
  select company_id 
  from company_relocation_histories 
  group by company_id
  having count(*) = 2
);

Edit : According to OP's comment

SELECT * 
FROM   companies 
WHERE  id IN (SELECT company_id 
              FROM   (SELECT company_id, 
                             Lead(relocation_location) OVER(ORDER BY id) x, 
                             Count(*) OVER (partition BY company_id) cnt 
                      FROM   company_relocation_histories) t 
              WHERE  x = 'FR' 
                     AND cnt = 2 
              GROUP  BY company_id); 

YOu could use a subquery for max(id) and count > 1

SELECT * 
FROM   `companies`  c
INNER JOIN company_relocation_histories h on c.id = h.company_id
INNER JOIN 
(
    SELECT company_id, Max(id)  max_id
    FROM   `company_relocation_histories` AS `sub` 
    group by company_id 
    having count(*) >1
) t on t.company_id = c.id 
        and t.max_id  = h.id 
          and h.relocation_location  ='FR'

In this way you have all the company with more than one location and related to the last location

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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