Search code examples
mysqlsqldatabasesql-match-all

Need help building MySQL SELECT query


So I have a table with columns:

deck_id, card_name, quantity, board(irrelevent for this question)

Each row has a deck id which is what I need, a card name, and amount of aforementioned cards.

It would look something like this:

101, "cardofblahblah", 3, "main"
101, "differentcard", 2, "main"
102, "cardofblahblah", 1, "main"
102, "fictionalcard", 3, "main"
102, "madeupcard", 4, "main"
103, "magicalcard", 2, "main"
103, "trickcard", 3, "main"
...
...

So that's what my database looks like. What I need is a select query that will return a deck id of a deck which contains all the cards I specify, for example: I need a deck which contains 1 copy of "madeupcard", and 3 copies of "cardofblahblah". That's what I really need done, but it would be great if someone would also mention how I can do > or < instead of only just setting the amount.

I know how to do the queries, but writing a complex one like this has me stumped.

Thanks for any help you guys can offer.'

EDIT: Just to clarify, I'm looking for deck id's of decks that contain ALL cards that I specify. For example, "which decks contain 3 copy of cardofblahblah AND 1 copy of madeupcard?"

Any kind of output where I can get the deck id's is good. The getting the deck id's is the primary concern for me.

EDIT2: I figured out the solution after going through various other topics on SO. However, I may not have the most efficient query, so if someone would improve it, that would be great.

SELECT table1.deck_id, table2.deck_id FROM decklist AS table1 
    JOIN (SELECT * FROM decklist WHERE card_name = "cardofblahblah" AND quantity = 3) 
    AS table2 ON table1.deck_id = table2.deck_id 
    WHERE table1.card_name = "madeupcard" AND quantity = 1;"

EDIT3: Thanks to Telarian. He gave me a better query.

SELECT  t.deck_id
FROM    decklist t
INNER JOIN  decklist l
    ON  l.deck_id = t.deck_id
WHERE   (t.card_name = "madeupcard" AND t.quantity >= 1)
        AND
        (l.card_name = "cardofblahblah" AND l.quantity >= 3)

Solution

  • It seems like this is being way over-complicated...

    Won't the following query give you what you want?

    SELECT  t.deck_id
    FROM    decklist t
        INNER JOIN  decklist l
            ON  l.deck_id = t.deck_id
    WHERE   (t.card_name = "madeupcard" AND t.quantity >= 1)
            AND
            (l.card_name = "cardofblahblah" AND l.quantity >= 3)