I have two tables:
game
`id` INT(11)
game_tags
`game` INT(11)
`tag_id` INT(11)
game_tags.game = game.id
I am horrible with MySQL, so here is my question: I want to be able to find what games
have a certain amount of tag_id
's. So if I have four tag_id
's (3, 5, 7, 11), I want to be able to find what games will have all four of those tags by looking through the game_tags
table. Here is an example of what I mean:
pseudo-MySQL:
SELECT *
FROM `games`
WHERE (search through game_tags table and find which rows have the same `game` field and all of the tag_id's that I need to search for)
LIMIT 0, 15
I know I explained this horrible (couldn't word it like in my mind), so if you have any questions, just leave a comment.
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.
To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.
MySQL SELECT statement is used to retrieve rows from one or more tables. The statement can also include UNION statements and subqueries. SELECT statement is used to fetch rows or records from one or more tables.
You can use group by
and having
clauses along with Bassam's query to ensure you have found all four ids for a given game.
select
game.*
from game
join game_tags on game.id = game_tags.game
where
tag_id in (3, 5, 7, 11)
group by
game.id
having
count(distinct tag_id) = 4;
Note that this works because the having
clause runs after the aggregation count(distinct ...)
runs, whereas a where
clause does not have this info.
SELECT games.*
FROM games
INNER JOIN
(SELECT game, COUNT(DISTINCT tag_id) AS gameCnt
FROM game_tags
WHERE tag_id in (3, 5, 7, 11)
GROUP BY game) t on games.id = game
WHERE gameCnt = 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With