【问题标题】:Select entries in MySQL在 MySQL 中选择条目
【发布时间】:2019-10-27 23:39:54
【问题描述】:

有 3 张桌子

新闻

+---------+---------------+---------------+--------------+-----------+--------+
| news_id |     title     |     short     |     body     | photo_id  | etc... |
+---------+---------------+---------------+--------------+-----------+--------+
|  881971 | Article Title | Article short | Article Body |    658998 |        |
|  881972 | Article Title | Article short | Article Body |    658999 |        |
+---------+---------------+---------------+--------------+-----------+--------+

期限

+-----+--------------+
| tid | news_term_id |
+-----+--------------+
|  14 |       881971 |
|   2 |       881972 |
|   2 |       881973 |
+-----+--------------+

照片

+--------+----------------------------------------+
|   id   |                  path                  |
+--------+----------------------------------------+
| 658998 | /files/2015/2/14304641562238139741.JPG |
| 658999 | /files/2015/2/14304641562238139742.JPG |
+--------+----------------------------------------+

我需要选择 News 表中的所有文章,其中 Term 中的 tid 等于 2(例如)并包含来自 的照片路径照片表格

我的查询:

select n.*, t.*
from news n
inner join term t 
    on n.news_id = t.news_term_id 
    and t.tid = 2

【问题讨论】:

  • 我们如何关联表photonews?我们可能需要在表photo 中像news_id 这样的列。
  • 在 News 表中有 photo_id 列,在 Photo 列中有 id 列等于 photo_id

标签: mysql sql phpmyadmin


【解决方案1】:

您当前的查询很好,您只需要引入photo 表。只需再添加一个联接:

select n.*, p.path
from term t
inner join news n on n.news_id = t.news_term_id
inner join photo p on p.phto_id = n.photo_id
where t.tid = 2

注意:我从term 表开始查询,因为我发现它使逻辑更清晰(过滤条件t.tid = 2 转到where 子句)。

【讨论】:

  • 谢谢,我尝试添加我现有的请求。但你的解决方案更好!您第二次帮助我,非常感谢!
  • 欢迎@CodePuch!我与您之前的问题无关,但现在我明白了。
猜你喜欢
  • 2021-04-08
  • 2021-10-31
  • 2011-03-08
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 2023-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多