我有两张不同的桌子:
档案(id,name,disp)
dossiers_etat(id,id_dossier,open,incharge,date)
dossiers_etat链接到1-N关系中的档案:1个档案可以链接到N档案 - etat,这要归功于一个联接:dossiers.id = dossiers_etat.id_dossier
我使用dossiers_etat作为记录我档案状态变化的时间表:今天可以打开1个档案=“Y”,但昨天打开=“N” 感谢dossiers_etat.date或dossiers_etat.id(上次日期和最后一次显示最新记录),我可以找到有关档案的最后记录。
如何完成此查询以获得在其最后记录中打开=“Y”和incharge =“ - ”的档案列表?
SELECT *
FROM dossiers
JOIN dossiers_etat
ON dossiers.id = dossiers_etat.id_dossier
WHERE dossiers.disp = "Y" AND dossiers_etat.open = "Y" AND dossiers_etat.incharge = "-"
ORDER BY dossiers.id DESC
非常感谢你的帮助!
答案 0 :(得分:1)
试试这个
SELECT *
FROM dossiers
JOIN dossiers_etat
ON dossiers.id = dossiers_etat.id_dossier
WHERE dossiers.disp = "Y" AND dossiers_etat.open = "Y" AND dossiers_etat.incharge = "-"
ORDER BY dossiers.id DESC
limit 1
答案 1 :(得分:1)
试试这个:
SELECT *
FROM dossiers B
JOIN dossiers_etat as C
ON B.id = C.id_dossier
WHERE B.disp = "Y" AND C.open = "Y" AND C.incharge = "-"
AND C.date = (SELECT max(date) from dossiers_etat WHERE id_dossier = C.id_dossier)
ORDER BY B.id DESC
答案 2 :(得分:1)
试试这个:
SELECT
*
FROM
dossiers
JOIN
dossiers_etat ON dossiers.id = dossiers_etat.id_dossier
WHERE
dossiers.disp = 'Y'
AND dossiers_etat.open = 'Y'
AND dossiers_etat.incharge = '-'
AND dossiers_etat.id = (SELECT
*
FROM
dossiers_etat
GROUP BY id_dossiers
ORDER BY date DESC)
ORDER BY dossiers.id DESC;
使用子选择,您将从档案表中的最后一个条目中获取ID。使用外部SELECT,您将获得打开正确条目的所有行,并且也在最后的记录中。