1

我有 2 个 mysql 表

表 1 是“qualitaet-inventar”,有 3000 行,“sachnummer”为 AUTO_INCREMENT


表 2 是“qualitaet”,有几行。这里“id”设置为 AUTO_INCREMENT,重要的是“sachnummer”可以存在很多次。(见图片中的红色标记)


我想做的是从“qualitaet”到“qualitaet-inventar”的左连接

我想通过在“qualitaet”上显示“创建”的最新日期来对所有“sachnummer”进行分组

并且当“qualitaet”中没有“sachnummer”时,对“qualitaet-inventar”进行空连接


所以我有这个代码

SELECT 
    i.`sachnummer` AS id,
    MAX(q.`created`) AS letztemessung,
    i.`sachnummer-name` AS sachnummer
FROM
        `qualitaet-inventar` i
LEFT JOIN
        `qualitaet` q on i.`sachnummer` = q.`sachnummer`
GROUP BY
        sachnummer
ORDER BY
    sachnummer ASC

问题是需要很长时间才能得到这个结果


使用此代码,它可以更快地工作

SELECT 
    q.`sachnummer` AS id,
    MAX(q.`created`) AS letztemessung,
    i.`sachnummer-name` AS sachnummer
FROM
    qualitaet q
LEFT JOIN
    `qualitaet-inventar` i on q.`sachnummer` = i.`sachnummer`
GROUP BY
    sachnummer
ORDER BY
    sachnummer ASC

但我没有得到这个代码的洞库存和空日期


对于高表行,是否有可能以更快的方式获得此表?:D

编辑:

这是我的索引

4

2 回答 2

1

以下不应该比您现有的查询更快 - 但根据您的描述,可能会:

SELECT i.`sachnummer` AS id,
       MAX(q.`created`) AS letztemessung,
       i.`sachnummer-name` AS sachnummer
FROM `qualitaet-inventar` i
JOIN `qualitaet` q on i.`sachnummer` = q.`sachnummer`
GROUP BY sachnummer
UNION ALL
SELECT i.`sachnummer` AS id,
       q.`created` AS letztemessung,
       i.`sachnummer-name` AS sachnummer
FROM `qualitaet-inventar` i
LEFT JOIN `qualitaet` q on i.`sachnummer` = q.`sachnummer`
WHERE q.`sachnummer` IS NULL
ORDER BY sachnummer ASC

另一种可能:

select id, max(letztemessung) as letztemessung, max(sachnummer) as sachnummer
from
(SELECT `sachnummer` AS id,
        `created` AS letztemessung,
        '' AS sachnummer
 FROM `qualitaet` q
 UNION ALL
 SELECT `sachnummer` AS id,
        cast(null as datetime) AS letztemessung,
        `sachnummer-name` AS sachnummer
 FROM `qualitaet-inventar` i
) sq
group by id 
ORDER BY sachnummer ASC
于 2013-04-21T18:59:32.397 回答
0

这是一般的想法,表名更短。

select somefields
from table1 t1 left join table2 t2 on t1.something = t2.something
join (
select something, max(datetimefield) maxdt
from table1
where whatever
group by something
)  t3 on t1.something = t3.something
and t1.datetimefield = maxdt
where whatever
于 2013-04-21T18:46:27.060 回答