左连接使用MySQL的企业的最新检查日期

时间:2017-09-02 23:06:31

标签: mysql sql

我有一个机构表,我想从检查表返回一个带有最新检验日期的结果集。现在我有:

SELECT business_table.business_name, business_table.address, inspection_table.date
FROM business_table
LEFT JOIN inspection_table ON business_table.id = inspection_table.business_id
WHERE inspection_table.date = (
    SELECT MAX(date)
    FROM inspection_table)

问题是我在最近的检查日期只得到一个结果。我需要返回所有的场所。查询将需要高效,因为我有大约600K的机构和3Million检查。

3 个答案:

答案 0 :(得分:1)

您正在使用外部联接。当业务记录没有匹配的检验记录时,则会创建一个空检验记录,而不是连接。因此,外部连接的检查记录将使所有列都为NULL。然后你有WHERE inspection_table.date = (...)。这会再次解除所有外连接记录,因为NULL永远不会匹配。

使用AND来使条件成为WHERE子句的一部分:

SELECT 
  b.business_name, 
  b.address,
  i.date
FROM business_table b
LEFT JOIN inspection_table i
           ON  i.business_id = b.id
           AND i.date        = (SELECT MAX(date) FROM inspection_table);

答案 1 :(得分:0)

我结束使用以下内容:

SELECT business_table.business_name AS Name, business_table.address AS Address, business_table.city AS City, business_table.state AS Province, inspection_table.rating AS Rating, inspection_table.date AS "Inspected"
FROM business_table
LEFT JOIN inspection_table ON business_table.id = inspection_table.business_id
WHERE inspection_table.date = (
    SELECT MAX(inspection_table.date)
    FROM inspection_table
    WHERE business_table.id = inspection_table.business_id)
ORDER BY inspection_table.date DESC

答案 2 :(得分:0)

啊,你根本不在寻找最新的检查日期。您正在寻找最新的检验日期每项业务

在您的解决方案中,您仍然使用不起作用的外部联接。不要那样做。要么使用外部联接并正确使用它,要么使用内部联接,如果你没事的话。

以下是如何使用外部联接获取每项业务的最新检查(因此您还显示尚未进行检查的企业):

SELECT 
  b.business_name, 
  b.address,
  i.date,
  ...
FROM business_table b
LEFT JOIN inspection_table i
           ON  i.business_id = b.id
           AND (i.business_id, i.date) IN 
           (
             SELECT business_id, MAX(date) 
             FROM inspection_table
             GROUP BY business_id
           );

与联接相同:

SELECT 
  b.business_name, 
  b.address,
  i.date, 
  ...
FROM business_table b
LEFT JOIN
(
  SELECT business_id, MAX(date) AS date
  FROM inspection_table
  GROUP BY business_id
) latest ON latest.business_id = b.id
LEFT JOIN inspection_table i
           ON  i.business_id = latest.business_id
           AND i.date        = latest.date;