[英]sql - query join 2 table with 1 table
抱歉,如果标题与我的问题无关。 我不知道这个的正确标题是什么。
所以我有 5 个表格,以便向用户显示相关内容
Data related content
Data related content's categories
Data related content's publishers
Data related user's followed categories
Data related user's followed publishers
如何根据用户的关注类别和关注的发布者显示内容,如果可能,如何区分内容是来自followCategory或followPublisher上的关系
例如:下面是我根据用户 FollowPublisher、cmiiw 显示内容的查询
SELECT content.id, content.description, ...etc
FROM followPublisher
LEFT JOIN publisher ON followPublisher.publisherId = publisher.id
LEFT JOIN contentPublisher ON publisher.id = contentPublisher.publisherId
RIGHT JOIN content ON contentPublisher.contentId = content.id
WHERE followPublisher.userId = 8
ORDER BY content.created desc;
以下是我根据用户 followCategory 显示内容的查询
SELECT content.id, content.description, ...etc
FROM followCategory
LEFT JOIN category ON followCategory.categoryId = category.id
LEFT JOIN contentCategory ON category.id = contentCategory.categoryId
RIGHT JOIN content ON contentCategory.contentId = content.id
WHERE followCategory.userId = 8
ORDER BY content.created desc;
如何结合这两个查询一次显示基于用户关注的类别和发布者的内容,或者有没有更好的方法而不是结合查询?
我认为您想要以下内容:
select content.* from content
LEFT JOIN contentPublisher ON content.id = contentPublisher.contentId
LEFT JOIN Publisher ON contentPublisher.publisherId = publisher.id
LEFT JOIN followPublisher ON publisher.id = followPublisher.publisherId
LEFT JOIN contentCategory ON content.id = contentCategory.contentId
LEFT JOIN category ON contentCategory.categoryId = category.id
LEFT JOIN followcategory ON category.id = followcategory.categoryId
where followPublisher.userId = 8 or followCategory.userId = 8
使用联合
有2个条件
不要按order by
使用任何与表相关的(idk 怎么说),而是使用as
重命名它。 在我的情况下, order by content.created
应该更改为content.created as contentCreated
,然后我们可以使用它来order by
。
添加默认值列以指示数据的来源(在这种情况下,无论是来自followPublisher
还是followCategory
)
询问:
SELECT content.id, content.description, content.created as contentCreated ...etc, 'publisher' as type
FROM followPublisher
LEFT JOIN publisher ON followPublisher.publisherId = publisher.id
LEFT JOIN contentPublisher ON publisher.id = contentPublisher.publisherId
RIGHT JOIN content ON contentPublisher.contentId = content.id
WHERE followPublisher.userId = 8
UNION
SELECT content.id, content.description, content.created as contentCreated ...etc, 'category' as type
FROM followCategory
LEFT JOIN category ON followCategory.categoryId = category.id
LEFT JOIN contentCategory ON category.id = contentCategory.categoryId
RIGHT JOIN content ON contentCategory.contentId = content.id
WHERE followCategory.userId = 8
ORDER BY contentCreated desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.