使用LIKE运算符而不限制结果

时间:2013-11-18 17:58:18

标签: mysql database-design

我有以下查询,其目的是显示包含一系列“标签”的“项目”列表。此外,我选择只为每个“项目”显示“5”标签,如下所示:

$query = mysql_query("SELECT i.*, 
                SUBSTRING_INDEX(GROUP_CONCAT(t.name), ',', 5) tagList
                FROM items AS i
                LEFT JOIN tag_rel AS tr ON (tr.item = i.id)
                LEFT JOIN tags AS t ON (t.id = tr.tag)
                GROUP BY i.id"); 

好的,那很好。它给了我这样的东西:

[ITEM 1] tag1,tag2,tag3,tag6,tag8

[ITEM 2] tag1,tag3,tag11,tag15,tag16

[ITEM 3] tag2,tag4,tag5,tag6,tag7

但事情就是这样:如果想通过添加以下内容显示“标记”为“ tag2 ”的“项目”列表:

WHERE (t.name LIKE 'tag2')

我的结果很简单:

[ITEM 1] tag2

[项目3] tag2

向我显示实际上标有“ tag2 ”的项目,但将“标记”限制为该标记。我真正想要的结果是这两个项目(标记为“ tag2 ”的项目)及其所有标签:

[ITEM 1] tag1, tag2 ,tag3,tag6,tag8

[ITEM 3] tag2 ,tag4,tag5,tag6,tag7

我尝试过使用

WHERE (tagList LIKE '%tag2%')

但那只是给了我:

Invalid query: Unknown column 'tagList' in 'where clause'

我希望自己清楚明白。非常感谢提前!

2 个答案:

答案 0 :(得分:1)

您错过了MySQL执行查询的顺序。通常,它首先执行FROM ... JOIN ...子句,然后执行WHERE子句,然后执行SELECT。因此,SELECT子句中创建的别名不能用于WHERE子句。

答案 1 :(得分:1)

您可以使用HAVING代替WHERE

来实现这一目标
SELECT i.*, 
    SUBSTRING_INDEX(GROUP_CONCAT(t.name), ',', 5) tagList
FROM items AS i
LEFT JOIN tag_rel AS tr ON (tr.item = i.id)
LEFT JOIN tags AS t ON (t.id = tr.tag)
GROUP BY i.id
HAVING (tagList LIKE '%tag2%')

如果你想搜索所有标签(不仅仅是前5个),你可以再次加入标签来做到这一点:

SELECT i.*, 
    SUBSTRING_INDEX(GROUP_CONCAT(t.name), ',', 5) tagList
FROM items AS i
JOIN tag_rel as tr2 ON (tr2.item = i.id)
JOIN tags as t2 ON (t2.id = tr2.tag)
LEFT JOIN tag_rel AS tr ON (tr.item = i.id)
LEFT JOIN tags AS t ON (t.id = tr.tag)
WHERE t2.name = 'tag2'
GROUP BY i.id

或与其他GROUP_CONCAT

SELECT i.*, 
    SUBSTRING_INDEX(GROUP_CONCAT(t.name), ',', 5) tagList
FROM items AS i
LEFT JOIN tag_rel AS tr ON (tr.item = i.id)
LEFT JOIN tags AS t ON (t.id = tr.tag)
GROUP BY i.id
HAVING (GROUP_CONCAT(t.name) LIKE '%tag2%')

您还应该知道LIKE解决方案也会匹配“tag2”,“tag21”,“myTag2”......等等。