ORDER BY RAND()不在UNION中工作

时间:2016-05-06 11:08:18

标签: mysql sql wordpress

我在UNION中遇到ORDER BY RAND()的问题。它似乎没有在UNION内的单独查询中随机排序。

我只想订购子查询而不立即对整个查询进行排序,因为订单需要是Subquery 1> subquery2> subquery3。

我已尝试过一些其他随机函数用于MySQL,如NEWID()和UUID(),但它们似乎也无法正常工作。

我使用WordPress获取结果。

SELECT *
        FROM (
                (SELECT act.wordpress_id,
                        act.title,
                        act.main_image,
                        loc.id,
                        "activities" AS type,
                        loc.town,
                        loc.village
                FROM tha_wc_activity act
                INNER JOIN tha_wc_location loc
                ON act.location_id = loc.id
                WHERE
                  act.active = 1 AND
                  act.visible_in_activities_overview = 1 AND
                  loc.id = 1
                ORDER BY RAND()
                )
            UNION
                (SELECT act.wordpress_id,
                        act.title,
                        act.main_image,
                        loc.id,
                        "activities" AS type,
                        loc.town,
                        loc.village
                FROM tha_wc_activity act
                INNER JOIN tha_wc_location loc
                ON act.location_id = loc.id
                WHERE
                  act.active = 1 AND
                  act.visible_in_activities_overview = 1 AND
                  loc.village = "villageName"
                ORDER BY RAND()
                )
            UNION
                (SELECT act.wordpress_id,
                        act.title,
                        act.main_image,
                        loc.id,
                        "activities" AS type,
                        loc.town,
                        loc.village
                FROM tha_wc_activity act
                INNER JOIN tha_wc_location loc
                ON act.location_id = loc.id
                WHERE
                  act.active = 1 AND
                  act.visible_in_activities_overview = 1 AND
                  loc.town = "townName"
                ORDER BY RAND()
                )
            ) AS act
            WHERE act.wordpress_id != 1
            LIMIT 0, 15)

更新 感谢Gordon Linoff,我发现我必须限制单独的子查询,否则它不会得到有序的结果

1 个答案:

答案 0 :(得分:1)

我不太清楚你的问题是什么。您在子查询中使用order by rand(),但随后选择了所有结果。获取所有行是所有行,无论它们的顺序如何。

然后,您正在使用union来删除重复项,并且还有其他逻辑。

据推测,你想要这样的东西:

select *
from (<subquery 1>
      union
      <subquery 2>
      . . .
     ) t
where . . .
order by rand()
limit 15;

除非您使用limit

,否则无需订购子查询

请注意,您可能希望使用union all而不是union - 除非您明确希望产生删除重复项的开销。