我不知道您的附件列表是什么样子(除了它有一个type
列),但这样的东西应该很接近,这意味着(a)它将返回所有行,以及(b)返回的附件值如果类型是,则为 null main
:
SELECT
r.*,
CASE WHEN at.name = 'main' THEN d.whatever ELSE NULL END AS attach_thingie
FROM record r
LEFT JOIN attachment d on d.record_id = r.id
LEFT JOIN attachment_type at on d.type_id = at.id
而且,正如上面评论中提到的@FreshPrinceOfSO,我认为不需要GROUP BY
.
还有一件事:根据我从查询中可以推断出的信息,我在三个表中没有看到任何明显的设计问题。我读到它record
可以有任意数量attachment
并且attachment
(也许)有 a type
。如果这是您的要求,那么您应该可以。
附录:根据列选择每条记录最多一个附件attachment.id
:
SELECT r.*, d.whatever
FROM record r
LEFT JOIN
(
SELECT attachment.record_id, MAX(attachment.id) AS Max_ID
FROM attachment
INNER JOIN attachment_type at ON attachment.type_id = at.id
WHERE at.name = 'main'
GROUP BY attachment.record_id
) att ON r.id = att.record_id
LEFT JOIN attachment d ON d.id = att.Max_ID