I’m working on a tags system, what it should do is you can have a query and selected tags, e.g. jquery and tags of javascript, library. It should only show related scripts with the query AND only that have the tags. This is the database layout:
Scripts table:
+-----------+---------------+
| script_id | name |
+-----------+---------------+
| 1 | jQuery |
| 2 | Sencha Touch |
| 3 | Codeigniter |
| 4 | Google Chrome |
| 5 | memcached |
| 6 | PHP |
| 7 | MooTools |
| 8 | node.js |
| 9 | jQuery Mobile |
+-----------+---------------+
Tags table:
+--------+-------------+-------------+
| tag_id | name | url_name |
+--------+-------------+-------------+
| 1 | JavaScript | javascript |
| 2 | Library | library |
| 3 | PHP | php |
| 4 | MySQL | mysql |
| 5 | Cache | cache |
| 6 | HTML | html |
| 7 | Open source | open-source |
+--------+-------------+-------------+
Tagged table:
+-----------+--------+-----------+
| tagged_id | tag_id | script_id |
+-----------+--------+-----------+
| 1 | 1 | 1 | # javascript -- jQuery
| 2 | 2 | 1 | # library -- jQuery
| 3 | 1 | 9 | # javascript -- jQuery mobile
+-----------+--------+-----------+
When I run my SQL, it still picks up jQuery Mobile but it shouldn’t because it doesn’t contain the library tag where jQuery does, I need it to constrain results that must meet the tags selected.
This is my SQL:
SELECT scripts.script_id,
scripts.name
FROM
(
scripts scripts
LEFT OUTER JOIN tagged tagged ON tagged.script_id = scripts.script_id
LEFT OUTER JOIN tags tags ON tags.tag_id = tagged.tag_id
)
WHERE MATCH(scripts.name) AGAINST ('jquery*' IN BOOLEAN MODE) AND ( tags.url_name = 'javascript' OR tags.url_name = 'library' )
GROUP BY script_id
ORDER BY scripts.name
LIMIT 0, 25
It returns:
+-----------+---------------+
| script_id | name |
+-----------+---------------+
| 1 | jQuery |
| 9 | jQuery Mobile |
+-----------+---------------+
If I change OR to AND, it won’t return anything at all or if I remove the brackets from the tags ( and ), it won’t return anything too.
How do I make the query constrain the tags?
Give this a try:
The only consideration with this is that the
2must be replaced with the amount of elements in theinclause.Here is the fiddle.