MySQL查询优化:UNION with rand()

时间:2014-02-10 17:16:37

标签: mysql

我有以下查询:

    (SELECT ad_code, ad_zone FROM on_ads WHERE ad_zone = 1 AND status = '1' ORDER BY RAND() LIMIT 1) UNION (SELECT ad_code, ad_zone FROM on_ads WHERE ad_zone = 2 AND status = '1' ORDER BY RAND() LIMIT 1);

它在我的服务器中被记录为慢查询。我正在尝试优化它。我尝试了以下查询

    (SELECT ad_code, ad_zone FROM on_ads WHERE ad_zone = 1 AND status = '1' OR ad_zone = 2 AND status = '1' ORDER BY RAND() LIMIT 2)

但是这个查询的问题是第一个选择了两个随机行,一个是ad_zone = 1,另一个是ad_zone = 2。虽然我选择了两行,但不能保证它会选择两个不同的行(一个是ad_zone = 1,另一个是ad_zone = 2)。 我该怎么做才能优化这个查询?

1 个答案:

答案 0 :(得分:0)

你必须尝试这样的事情:

(SELECT DISTINCT(ad_code), ad_zone FROM on_ads WHERE (ad_zone = 1 OR ad_zone = 2) AND status = '1' ORDER BY RAND() LIMIT 2)