用sql查询获取所有标签

时间:2012-07-03 10:54:18

标签: php sql

我有这个sql是由其他人帮助的。

$sql ="
select e.*, i.*, group_concat( t.tag separator ',') as tag_list
from nv_entries e
JOIN nv_tags t on t.entrie_id = e.id
LEFT JOIN nv_images i on i.entrie_id = e.id

where t.tag in ( $tag_list )
group  by e.id
having count(t.id) = $num_tags ";

结果就是这个(我只在这里显示一个,可能更多):

[1] => Array
        (
            [id] => 2
            [band] => Kids for Cash
            [album] => No More Walls E.P.
            [label] => 
            [year] => 1986
            [text] => Text about album kids for cash.
            [entrie_id] => 2
            [source] => img02_9lch1.png
            [tag_list] => tree
        )

对于标签,我必须显示entrie具有的所有标签,并突出显示用于获取结果的标签。在这种情况下,[tag_list] => tree仅显示一个标记,即搜索字段中使用的标记。我的问题是,我怎样才能得到这样的结果?:

            ...
            [tag_list] => tree, green, foo, bar
            [used_tags] => tree
        )

由于数组也很好,但是当它只是一个项目时请同时请一个数组。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,请在条件

中使用> =
$sql ="
select e.*, i.*, group_concat( t.tag separator ',') as tag_list
from nv_entries e
LEFT JOIN nv_images i on i.entrie_id = e.id
JOIN nv_tags t on t.entrie_id = e.id

where t.tag in ( $tag_list )
group  by e.id
having count(t.id) >= $num_tags ";

ADD

子查询方法:

$sql ="
select e.*, i.*, group_concat( t.tag separator ',') as tag_list
from nv_entries e
JOIN nv_tags t on t.entrie_id in (
select se.id 
from nv_entries se
JOIN nv_tags st on st.entrie_id = se.id

where st.tag in ( $tag_list )

group  by se.id
having count(st.id) >= $num_tags

)
    LEFT JOIN nv_images i on i.entrie_id = e.id
    WHERE 1
    group by e.id
 ";

进入子查询我得到至少请求标签的entrie havin的ID列表,然后在主查询中我得到所有的infox

添加固定查询(参见提问者评论)

子查询方法,修复“e”和“t”之间丢失的连接:

$sql ="
select e.*, i.*, group_concat( t.tag separator ',') as tag_list
from nv_entries e
JOIN nv_tags t on t.entrie_id = e.id 
    LEFT JOIN nv_images i on i.entrie_id = e.id
    WHERE e.id in  (
select se.id 
from nv_entries se
JOIN nv_tags st on st.entrie_id = se.id

where st.tag in ( $tag_list )

group  by se.id
having count(st.id) >= $num_tags

)
    group by e.id
 ";