我使用的是帖子表,学校和用户可以使用两种类型的实体向该表添加内容。帖子表中有一个post_from字段,用于区分帖子是来自用户还是来自学校。
我想写一个查询,并根据post_from字段加入到用户表或学校表。
SELECT *
FROM post
LEFT JOIN `user`
ON (user.id = post.uid AND post.post_type = 'user' )
LEFT JOIN school_profile
ON (school_profile.id = post.school_id AND post.post_type = 'school')
答案 0 :(得分:1)
您可以通过并集进行操作:
SELECT post.*
FROM post
INNER RJOIN `user`
ON (user.id = post.uid AND post.post_type = 'user' )
union
SELECT post.*
FROM post
INNER JOIN school_profile
ON (school_profile.id = post.school_id AND post.post_type = 'school')
或者,您可以执行以下操作:
SELECT *
FROM post
LEFT JOIN `user` ON (user.id = post.uid)
LEFT JOIN school_profile ON (school_profile.id = post.school_id)
WHERE post.post_type IN ('user', 'shcool')