Php 合并表MySql
我想知道如何在mysql中连接不同的表。例如,包含各种列的文章表、收藏夹文章表、注释表和收藏夹注释表。我想在一页上列出文章和最喜欢的评论。我怎么办? 条款表:Php 合并表MySql,php,mysql,sql,inner-join,where-clause,Php,Mysql,Sql,Inner Join,Where Clause,我想知道如何在mysql中连接不同的表。例如,包含各种列的文章表、收藏夹文章表、注释表和收藏夹注释表。我想在一页上列出文章和最喜欢的评论。我怎么办? 条款表: id id_user unique_id 1 1 dhdej4 2 1 sr4r44 id id_article_favorite id_user_favorite 1 1 1 2
id id_user unique_id
1 1 dhdej4
2 1 sr4r44
id id_article_favorite id_user_favorite
1 1 1
2 2 1
文章翻译表:
id id_article article lang
1 1 something en
2 2 something en
收藏夹文章表:
id id_user unique_id
1 1 dhdej4
2 1 sr4r44
id id_article_favorite id_user_favorite
1 1 1
2 2 1
标签表:
id hashtag
1 something
2 something
id id_hashtag_favorite id_user_favorite
1 1 2
2 2 2
收藏夹标签表:
id hashtag
1 something
2 something
id id_hashtag_favorite id_user_favorite
1 1 2
2 2 2
我想合并所有这些表,我尝试了以下方法:
SELECT *
FROM article a
JOIN article_translation t
ON a.id = t.id_article
JOIN favorite_article fa
ON fa.id_article_favorite = t.id_article
JOIN hashtag h
JOIN favorite_hashtag fh
ON fh.id_favorite_hashtag = h.id
WHERE fa.id_user_favorite = 1
AND t.lang = 'en'
AND fh.id_user_favorite = 1
我想你想要:
select *
from article a
inner join article_translation at on at.id_article = a.id
inner join favorite_article fa on fa.id_article_favorite = a.id
inner join comment c on c.id_article_comment = a.id
inner join favorite_comment fc on fc.id_comment_favorite = a.id
where fa.id_user_favorite = 1 and at.lang = 'en'
我试图修复表之间的连接条件。大概所有与文章相关的表都是通过外键约束的。您可能希望根据您的实际模式来检查这一点
我还添加了表别名,这使查询更易于编写和读取
我建议您在select
lause中枚举所需的列,而不是使用select*
;这使查询的意图更加清晰,并使您有机会对名称不唯一的列进行别名。请向我们显示您希望此示例数据的结果。您应该为注释提供一个ON
子句。很抱歉,我更正了表中的一个错误(我尝试对此进行简化,但我错了)。假设comments表实际上是hashtag表(hashtag和articles表没有任何共同点)。很抱歉again@Gae:您的问题不太清楚表格之间的关系。您可能需要在这个答案的基础上为您的用例生成适当的查询。