SELECT items.title, items.subtitle, items.ebay_id AS item_id, items.actual_price AS actual_price, items.max_bid, items.image_url, user_settings.category, user_settings.minbid, user_settings.maxbid, user_settings.item_condition, user_settings.max_items_to_buy FROM `users` LEFT JOIN user_settings ON ( users.ID = user_settings.user_id) LEFT JOIN items ON ( items.primary_category = user_settings.category) LEFT JOIN placed_bids ON (placed_bids.user_id = users.ID AND user_settings.category = placed_bids.category AND placed_bids.ebay_id = items.ebay_id) WHERE users.ebay_name ='".$GET_ARRAY["user_id"]."' AND ( user_settings.minbid >= items.actual_price OR user_settings.minbid < 1 ) AND ( user_settings.maxbid <= items.actual_price OR user_settings.maxbid <1 ) AND user_settings.category = items.primary_category AND items.item_closed=0 AND items.actual_price < items.max_bid AND item_ends + INTERVAL 1 HOUR > NOW( ) having (SELECT count(*) from placed_bids WHERE user_id = users.ID AND high_bid =1 and category = items.primary_category group by category) < user_settings.max_items_to_buy ORDER BY RAND() LIMIT 1