多个表上的MySQL子查询错误

时间:2012-05-17 00:19:06

标签: mysql

我有3个表格帖子,术语和关系。

帖子表:

ID     title      
1      abc
2      cdf

条款表:

term_id  slug
1        jeans
2        shirts

关系表:

object_id    taxonomy_id
1             1
2             1

MySQL查询我曾经尝试列出与其相关的“牛仔裤”的标题

SELECT posts.title 
FROM posts, terms, relationships
WHERE (SELECT terms.term_id FROM terms WHERE terms.slug LIKE '%jeans%')
AND (SELECT relationships.object_id FROM relationships WHERE terms.term_id = relationships.taxonomy_id)
AND (posts.ID = relationships.object_id)

它给了我错误#1242 - 子查询返回超过1行。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT posts.title
FROM posts INNER JOIN relationships ON (posts.ID = relationships.object_id)
           INNER JOIN terms ON (terms.term_id = relationships.taxonomy_id)
WHERE terms.slug LIKE '%jeans%';

我没有你的桌子,所以我无法测试,但我认为这应该有效。

答案 1 :(得分:0)

尝试这样的事情:

SELECT p.title 
  FROM posts p
  JOIN relationships r
    ON r.object_id = p.ID
  JOIN terms t
    ON t.term_id = r.taxonomy_id 
 WHERE t.slug LIKE '%jeans%'

答案 2 :(得分:0)

SELECT posts.title
FROM posts 
    INNER JOIN relationships ON (posts.ID = relationships.object_id)
    INNER JOIN terms ON (terms.term_id = relationships.taxonomy_id)
WHERE 
    (terms.slug LIKE '%jeans%')
AND 
    (terms.term_id = relationships.taxonomy_id)
AND 
    (posts.ID = relationships.object_id)