开发者

php mysql inventory

I'm creating an app for a trading card game called Magic: the Gathering and I have made a query that checks all user-submitted decks and gives you the percentage of cards you have in your inventory over the cards in the deck. But my problem is, it does this for all the decks on the database. What I want to do is only return the decks which I already have 50% of the cards for.

Here is the query:

SELECT
SUM(t.qty_inv) / t.deck_cards completed,
t.deck_id
FROM (
  SELECT
  CASE WHEN m.qty_inv IS NULL THEN 0 WH开发者_Python百科EN m.qty_inv > dc.card_qty THEN dc.card_qty ELSE m.qty_inv END qty_inv,
  dc.deck_id,
  d.deck_cards
  FROM mtgb_test.decks d
  INNER JOIN mtgb_test.decks_cards dc ON (d.deck_id = dc.deck_id)
  LEFT OUTER JOIN (
    SELECT
    COUNT(*) qty_inv, item_print_id print_id
    FROM mtgb_test.inventories_items
    WHERE item_user_id = 1
    GROUP BY item_print_id
  ) m ON (m.print_id = dc.card_print_id)
) t
GROUP BY deck_id
ORDER BY completed DESC;

The problem with this query is that I can't use the derived completed field in the where clause like so:

WHERE completed > 0.5

I don't know if variables can solve this problem, I tried a bit but it got mished mashed as I'm very new to user-defined variables.

Edit: Some good people answered below that I needed to have the HAVING syntax, and that is the correct and obvious answer. I'd just probably choose the best answer to the postscript question then.


Another thing, if I had 200,000 decks in my database and I had 2,000 cards in my inventory, I'm fine with this query looping through all those and finding which decks I already had half of the cards for. But my problem is with the LEFT OUTER JOIN. I don't know about how MySQL really works inside but maybe someone who does can point it out. When looping through all the 200,000 decks, would it do the left join for every deck there is or will it be smart enough to cache this so that it only queries my inventory items once?

Thanks in advance,

Ramon


You can use HAVING completed > 0.5 to further reduce the amount of rows returned. You can read more about HAVING clause at http://dev.mysql.com/doc/refman/5.5/en/select.html.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜