首页 > 解决方案 > 合并表 MySql

问题描述

我想知道如何在mysql中加入不同的表。例如,具有各种列的文章表、收藏文章表、评论表和收藏评论表。我想在一页上列出文章和最喜欢的评论。我该怎么办?文章表:

id   id_user        unique_id
1    1              dhdej4      
2    1              sr4r44

文章翻译表:

id   id_article     article     lang
1    1              something   en   
2    2              something   en

最喜欢的文章表:

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

我想让所有这些表合并,我试过这个:

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

标签: phpmysqlsqlinner-joinwhere-clause

解决方案


我想你想要:

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'

我试图修复表之间的连接条件。想必,所有相关的表都article通过外键约束。您可能想根据您的实际架构来查看它。

我还添加了表别名,这使查询更易于编写和阅读。

我建议在selectlause 中枚举您想要的列,而不是使用select *; 这使查询的意图更清晰,并让您有机会为名称不唯一的列设置别名。


推荐阅读