So, I have an active record query that I’m doing in PHP under the Codeigniter framework where I want to select all of the entries (named ‘tracks’ below) where a certain value in a join is met (‘tags’ that are associated with the tracks – each track can have multiple tags tied to it). What I’m wondering is if there’s a way to have the query look for tracks that have ALL of the selected tags associated with it. So, instead of having it get all tracks that have a links.tag_id of 1, then get all tracks with a links.tag_id of 2, it returns all tracks that have a links.tag_id of 1 as well as 2. Essentially, it’s a subtractive query where it narrows the chosen results down the more tags that you add. Here’s what I have going thus far:
$this->db->select('tracks.id,
tracks.name AS name,
tracks.filename,
tracks.url_name,
tracks.file_path_high,
tracks.filesize,
tracks.categories,
tracks.duration,
tracks.folder,
links.tag_id,
SUM(links.weight) AS total_weight,
tag_data.tag_name');
$this->db->distinct();
$this->db->from('music AS tracks');
$this->db->where_in('links.tag_id', array('1', '2');
$this->db->join('linked_tags AS links', 'links.track_id = tracks.id', 'inner');
$this->db->join('tags AS tag_data', 'tag_data.id = links.tag_id', 'inner');
What you need is to join your tags table many times for each tag you want to find and use each tags alias in your where clause. For example i’d do this:
Obviously, i don’t know what you structure looks like, but you’re a brilliant fellow and will surely understand how to adapt it to your structure…
What this does is INNER JOIN the LINKED_TAGS and TAGS table many times and forces the INNER JOIN to be done on a specific tag. If the tag cannot be found for a specific object, the inner join will fail and thus will simply not be returned… You can add as many JOINS like these that you want but obviously, at a certain point, it can inccur on query performance.
For more example on how to use this same technique, view the follow post:
Advanced MySQL Joining. Speeding up query
Good luck