SQL连接与上次日期

时间:2018-01-18 10:58:41

标签: mysql sql

您好我尝试将表格中的类型连接到2列,这些列给出了多行,所以这不起作用

SELECT t1_id, t1.Company  t1_some_field, t2_type 
FROM t1 
LEFT JOIN t2 ON t1.Company = t2.Company AND t1_id = t2_t1_id

表格t2

t2.Company + t2_t1_id的行乘以t2_date

我需要加入t2_type与最后t2_date

我这样做

SELECT t1_id, t1.Company  t1_some_field, t2_type 
FROM t1 
LEFT JOIN t2
ON t1.company = t2.company 
AND t1_id = t2.t2_t1_id
LEFT JOIN
    (SELECT MAX(t2_date) AS Last_Date, company, t2_t1_id
        FROM t2
        GROUP BY company, t2_t1_id) last_t2
ON t1.company = last_t2.company 
AND t1_id = last_t2.t2_t1_id

WHERE t2_date = Last_Date;

看起来像这样,但我认为应该是一种更简单的方法。

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT t1_id, t1.Company t1_some_field, 
    (SELECT t2_type 
    FROM t2
    WHERE t2.t2_t1_id = t1.id
    AND t1.company = t2.company
    AND NOT EXISTS(
        SELECT 'NEXT'
        FROM t2 t2next
        WHERE t2.t2_t1_id = t2next.t2_t1_id
        AND t2.company = t2next.company
        AND t2.t2_date > t2next.t2_date)
    )
FROM t1 

答案 1 :(得分:1)

可以按如下方式重写,但是,它可能会导致与您的情况相同的查询计划

SELECT t1_id, t1.Company  t1_some_field, t2_type 
FROM t1 
LEFT JOIN t2
ON t1.company = t2.company 
AND t1_id = t2.t2_t1_id
WHERE t2.t2_date =
    (
        SELECT MAX(t2_date) 
        FROM t2
        WHERE t1.company = t2.company AND 
              t1.t1_id = t2.t2_t1_id
        GROUP BY company, t2_t1_id
    ) 

如果您有MySQL支持窗口功能(自8.0.0版本起),那么使用row_number还有另一种方法,但我建议使用您的解决方案。

答案 2 :(得分:1)

使用substring_index() / group_concat()时,有一种方法是黑客攻击:

SELECT t1.t1_id, t1.t1.Company, t1.t1_some_field, last_t2.t2_type 
FROM t1 LEFT JOIN t2
     (SELECT MAX(t2_date) AS Last_Date, company, t2_t1_id,
             SUBSTRING_INDEX(GROUP_CONCAT(t2.t2_type ORDER BY t2.t2_date DESC), ',', 1) as last_t2_type
      FROM t2
      GROUP BY company, t2_t1_id
     ) last_t2
     ON t1.company = last_t2.company AND t1_id = last_t2.t2_t1_id;

另一种方法使用相关子查询:

select t1.*,
       (select t2.t2_type
        from t2
        where t1.company = t2.company and t1.t1_id = t2.t2_t1_id
        order by t2.t2_date desc
        limit 1
       ) as t2_type
from t1;

使用t2(company, t2_t1_id, date)上的索引,可能会获得最佳效果。