MySql查询,如何将conditon放在同一个表的Union查询中

时间:2016-03-14 05:40:19

标签: mysql select

select * from 
(
   (select * from advertisement
    where fk_country='178' and ad_start_date <= '2016-03-14' and 
    ad_end_date>='2016-03-14' order by RAND() limit 3
   )

  UNION

  (select * from advertisement
   where  ad_start_date <= '2016-03-13' and ad_end_date>='2016-03-13' 
   order by RAND() limit 3
  ) 
)as leftpanelad order by rand() limit 3;

这个查询工作得很好并且获取了三个记录。我的问题是,如果第一个选择查询的记录与fk_country退出,它应该从第一个查询返回三个记录仅针对该国家ID,第二个查询应该返回平衡记录如果第一个查询的记录少于三个。

1 个答案:

答案 0 :(得分:1)

尝试此查询:

select * from advertisement
where 
    case    when exists(select * from advertisement
                        where fk_country='178' and ad_start_date <= '2016-03-14' and 
                        ad_end_date>='2016-03-14' limit 2,1)
                then 
                    fk_country='178' and ad_start_date <= '2016-03-14' and 
                    ad_end_date>='2016-03-14'
            else 
                ad_start_date <= '2016-03-13' and ad_end_date>='2016-03-13' 
    end
limit 3;