php - 合并表 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
解决方案
我想你想要:
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 *
; 这使查询的意图更清晰,并让您有机会为名称不唯一的列设置别名。
推荐阅读
- javascript - ConnectFunction 创建的组件中的元素类型无效
- docker - 在 Kubernetes 上启动 Spark 3.0 -- 拉取镜像时出错
- android - 如何在图表线android上方添加渐变颜色?
- ios - Xcode11禁用暗模式
- flutter - 如何绘制这样的自定义颤振边框?
- postgresql - 自定义功能:将对象插入表格
- java - spring batch 提供作业执行状态和步骤信息
- android - RatingBar - 当触摸 RatingBar 时,星星会被填满
- jquery - 不能同时从 jquery 日期选择器中选择两个日期
- python - 无法从“Adafruit_DHT”导入名称“Beaglebone_Black_Driver”