【问题标题】:Merge tables MySql合并表 MySql
【发布时间】:2020-10-13 21:27:57
【问题描述】:

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

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

【问题讨论】:

  • 请向我们展示您想要的样本数据结果。
  • 你应该有一个ON 子句用于comment

标签: php mysql sql inner-join where-clause


【解决方案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'

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

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

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

【讨论】:

  • 很抱歉,我更正了表格中的一个错误(为此我试图简化,但我错了)。假设 cmets 表实际上是 hashtag 表(hashtag 和articles 表没有任何共同点)。再次抱歉
  • @Gae:您的问题不太清楚表格之间的关系。您可能需要在此答案的基础上为您的用例生成正确的查询。
猜你喜欢
  • 1970-01-01
  • 2015-11-12
  • 2011-04-11
  • 2012-12-22
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多