具有条件的三个表上的内部连接


INNER JOIN on three tables with condition

我正在尝试从标签 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
|-----------------------|

这是我的MySQL代码,用于内部连接所有表并从标签中获取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

无论如何查询不正确,我不明白 INNER JOIN 应该如何在这里工作,知道吗?谢谢

SQL 具有特定的子句顺序。 在您的情况下:

  • 选择
  • 哪里
  • 分组依据
  • 订购方式
  • 限制

始终是查询中的排序。 请注意,JOIN表达式不是"子句"。 它们是FROM子句的一部分(在MySQL中,updatedelete子句也是如此)。

应用于您的查询:

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  

您会注意到,缩进突出显示了作为语言基本部分的子句。

我还添加了表别名,使查询更易于编写和读取。 并修复了一些小问题,例如放错位置的逗号。

我注意到您从数据中提取了太多列。 您应该只列出所需的列(可能p.*)。

试试这个。

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