简体   繁体   English

在有条件的三张桌子上进行内联接

[英]INNER JOIN on three tables with condition

I am trying to fetch all the photos detail from a tag slug (URL for the tag) , the database has three tables: 我正在尝试从一个标签slug (该标签的URL)中获取所有照片的详细信息,该数据库具有三个表:

|-----------------------|
|==> photo              |
|   -> id               |
|   -> custom_id        |
|   -> title            |
|-----------------------|
|==> tags               |
|   -> id               |
|   -> slug             |
|-----------------------|
|==> tags_relation      |
|   -> tid              | <-- this is the tags.id
|   -> pid              | <-- this is the photo.custom_id
|-----------------------|

here is my mysql code to INNER JOIN all the tables and to get 20 photos from a tag: 这是我的mysql代码以INNER JOIN所有表并从标签中获取20张照片:

SELECT photo.*, tags.*, tags_relation.*, 
FROM tags WHERE tags.slug = 'people' 
INNER JOIN tags_relation ON = tags_relation.tid = tags.id 
INNER JOIN photo ON photo.custom_id = tags_relation.pid
LIMIT 20  
ORDER BY photo.date DESC

The query is not correct anyway, and i can't understand how the INNER JOIN should work here, any idea? 无论如何,查询都不正确,我不明白INNER JOIN应该如何在这里工作,有什么想法吗? Thanks 谢谢

SQL has a specific ordering of clauses. SQL具有子句的特定顺序。 In your case: 在您的情况下:

  • SELECT 选择
  • FROM
  • WHERE 哪里
  • GROUP BY 通过...分组
  • ORDER BY 订购
  • LIMIT 限制

This is always the ordering within a query. 始终是查询中的顺序。 Note that JOIN expressions are not "clauses". 请注意, JOIN表达式不是“子句”。 They are part of the FROM clause (and in MySQL, the update and delete clauses as well). 它们是FROM子句的一部分(在MySQL中,也是updatedelete子句)。

Applied to your query: 应用于您的查询:

SELECT p.*, t.*, tr.*
FROM tags t INNER JOIN
     tags_relation tr
     ON tr.tid = t.id INNER JOIN
     photo p
     ON p.custom_id = tr.pid
WHERE t.slug = 'people' 
ORDER BY p.date DESC
LIMIT 20  

You will note that the indentation highlights the clauses which are a fundamental part of the language. 您会注意到缩进突出显示了作为语言基本部分的子句。

I also added table aliases, which make the query easier to write and to read. 我还添加了表别名,这使查询更易于编写和阅读。 And fixed some minor things, such as misplaced commas. 并修复了一些小问题,例如放错逗号。

I note you are pulling too many columns out of the data. 我注意到您正在从数据中提取太多列。 You should just list the columns you want (probably p.* ). 您应该只列出所需的列(可能是p.* )。

try this.. 尝试这个..

SELECT photo.*, tags.*, tags_relation.* 
    FROM tags WHERE tags.slug = 'people' 
    INNER JOIN tags_relation ON(tags_relation.tid = tags.id) 
    INNER JOIN photo ON (photo.custom_id = tags_relation.pid)
    ORDER BY photo.date DESC
    LIMIT 20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM