有几个选项可用。一个在帖子中提到。选择将是这样的:
select * from
cars a
left join users u on (a.person_type='user' and a.person_id=u.id)
left join visitors v on (a.person_type='visitor' and a.person_id=v.id)
另一种选择是代替person_type
andperson_id
简单地同时拥有user_id
and visitor_id
。两者都是可空的,您甚至可以在它们上放置一个强大的外键。选择非常相似:
select * from
cars a
left join users u on (a.user_id=u.id)
left join visitors v on (a.visitor_id=v.id)
最后但同样重要的是,也许您可以将users
andvisitors
表合并到一个表中?
[cars]
ID | car_name | person_id
-----+----------+-------------
1 | car 1 | 1
2 | car 2 | 2
[persons]
ID | type | name
-----+---------+----------
1 | user | person 1
2 | visitor | person 2
然后选择变得超级简单:
select * from cars c join persons p on (c.person_id=p.id)