Welcome Guest, Not a member yet? Register   Sign In
[SOLVED] Funky DB Query
#11

[eluser]vitoco[/eluser]
when i'm not sure how many values am i adding ( as conditions ) to the query, i do this :

Code:
// HERE IS HARCODED, BUT YOU CAN ADD ITEMS ( CONDITIONS ) TO THE ARRAY OF TAGS INSIDE YOUR "IFs"
$tags = array( 40 , 19 , 15, 0 ) ;
//
$sql = "
SELECT
    * ,
    COUNT( tag_id ) AS num_tags ,
    GROUP_CONCAT( tag_id ) AS tags
FROM
    restaurants
INNER JOIN
    tag_restaurants_rel
ON
    tag_restaurants_rel.restaurant_id = restaurants.restaurant_id
WHERE
    tag_restaurants_rel.tag_id    IN ( ".implode( ',' , $tags )." )
GROUP BY
    restaurants.restaurant_id
HAVING
    num_tags = ".count( $tags )."
ORDER BY
    rest_name asc
" ;

The result, a dynamic number of tags to match, the only limitation is that it must be at least one,if not the query resulting is invalid

Code:
....
WHERE
    tag_restaurants_rel.tag_id    IN ()   <--- SQL SYNTAX ERROR
GROUP BY
    restaurants.restaurant_id
HAVING
    num_tags = 0
...

Saludos
#12

[eluser]loganbest[/eluser]
OK, so I rewrote the query in active record syntax and got this query returned. I also do not get any data back from that query though I know there is data for that query.

Code:
SELECT *, COUNT( tag_id ) AS num_tags, GROUP_CONCAT( tag_id ) AS tags
FROM (`restaurants`)
INNER JOIN `tag_restaurants_rel` ON `tag_restaurants_rel`.`restaurant_id` = `restaurants`.`restaurant_id`
WHERE `tag_restaurants_rel`.`tag_id` IN ('40,19')
GROUP BY `restaurants`.`restaurant_id`
HAVING `num_tags` =  2
ORDER BY `rest_name` asc
#13

[eluser]vitoco[/eluser]
of course you don't get any data returned, cause this
Code:
...
WHERE `tag_restaurants_rel`.`tag_id` IN ('40,19')
....
it's not the same with this

Code:
// AS INT
...
WHERE `tag_restaurants_rel`.`tag_id` IN (40 , 19)
....

// AS STRING
WHERE `tag_restaurants_rel`.`tag_id` IN ('40' ,'19')

Saludos
#14

[eluser]loganbest[/eluser]
ah shit. didn't even see that. it works! thanks much.

for the record I took out implode() because I already formatted the array correct.
#15

[eluser]vitoco[/eluser]
you're welcome, please add [SOLVED] to the title

Saludos




Theme © iAndrew 2016 - Forum software by © MyBB