我有MySQL查询,大约需要25秒。行数不多(大约200行),但我不明白为什么需要很长时间。
查询:
SELECT *
, c.id c_id
FROM campaign c
JOIN campaign_category cc
ON c.campaign_type = cc.id
WHERE c.is_deleted = 0
AND c.status = 1
AND c.id NOT IN (SELECT campaign_id FROM user_reviews WHERE user_id = 4)
AND c.amt_req > (SELECT COUNT(id)
FROM reserved_reviews
WHERE camping_id = c.id
AND user_id != 4)
+ (SELECT COUNT(id)
FROM user_reviews
WHERE campaign_id = c.id)
编辑: 我尝试了这样的JOIN,但没有结果:
SELECT *, `c`.`id` as `c_id`,COUNT(`ur`.`id`) as `total_reviewed`, COUNT(`rr`.`id`) as `total_reserved` FROM `campaign` `c` JOIN `campaign_category` `cc` ON `c`.`campaign_type`=`cc`.`id` JOIN `user_reviews` `ur` ON `ur`.`campaign_id`=`c`.`id` JOIN `reserved_reviews` `rr` ON `rr`.`camping_id`=`c`.`id` WHERE `c`.`is_deleted` =0 AND `c`.`status` = 1 AND `ur`.`user_id` != 4 GROUP BY `c`.`id` HAVING `c`.`amt_req` > COUNT(`ur`.`id`) + COUNT(`rr`.`id`)
编辑:表结构:第一个图像 - user_reviews表,第二个图像campagin表,第三个图像:reserved_reviews表。
答案 0 :(得分:0)
您可以使用索引改进此查询;
SELECT *, c.id c_id
FROM campaign c JOIN
campaign_category cc
ON c.campaign_type = cc.id
WHERE c.is_deleted = 0 AND
c.status = 1 AND
c.id NOT IN (SELECT campaign_id FROM user_reviews WHERE user_id = 4)
c.amt_req > (SELECT COUNT(*)
FROM reserved_reviews
WHERE campaign_id = c.id AND user_id <> 4)
) +
(SELECT COUNT(id)
FROM user_reviews
WHERE campaign_id = c.id
) ;
对于外部查询和连接:campaign(status, is_deleted, id, amt_req)
和campaign_category(id)
(如果将后者定义为主键,则应该使用后者。
然后:user_reviews(user_id, campaign_id)
,reserved_reviews(campaign_id, user_id)
和user_reviews(campaign_id)
。