简体   繁体   中英

get all tags with sql query

I have this sql that is made by help of others.

$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 ";

The result is this (i only show one entrie here, could be more):

[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
        )

For the tags, i have to show all tags that a entrie has and highlight the tags that where used to get the result. In this case [tag_list] => tree only shows one tag, the one that was used in the search field. My question is, how can i get a result like this?:

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

As a array is also good, but then please also an array when it's just one item.

If I understood correctly use >= in the having condition

$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

subquery approach:

$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
 ";

Into subquery I get the ID list of entrie havin at least requested tags, then in main query I get all infox

ADD fixed query (see asker comment)

subquery approach, fix the lost join between "e" and "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
 ";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM