INNER JOIN在三个有条件的桌子上

时间:2015-03-13 10:23:01

标签: php mysql inner-join

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

无论如何,查询不正确,我无法理解INNER JOIN在这里应该如何运作,任何想法? 感谢

2 个答案:

答案 0 :(得分:1)

SQL具有特定的子句排序。在你的情况下:

  • 选择
  • FROM
  • WHERE
  • GROUP BY
  • ORDER BY
  • LIMIT

总是查询中的排序。请注意,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.*)。

答案 1 :(得分:0)

试试这个..

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
相关问题