使用此查询选择mysql然后用这个查询填充?

时间:2012-03-14 13:24:45

标签: mysql select union

我正在尝试使用mysql查询从表中选择一些新闻故事,现在关键是我总是需要5个结果。

所以我希望能够用另一个where子句填充我的结果,即

select * from here where this = 1
if there is < 5 results then select * from here where this = 2
limit [how ever many we are short say the first query brings back 3 results this should bring back 2]

现在我已经看过使用联盟来做这个但没有外界帮助,即从php和另一个查询计算结果我认为不可能,我知道我可以简单地使用php来做到这一点,并且可能最终会这样做,但我只是想知道我想用一个mysql查询做什么是可能的?

编辑:

它也需要按日期排序,但它们并没有真正按顺序发布

按日期排序最多5,其中这= 1,如果没有5,请将其填充,其余的地方= 2也按日期排序。

另一个可耻的编辑:

问一个愚蠢的问题大笑......这是我的睡眠剥夺我只是假设桌子上有数据而前一个程序员正在使用工会做各种各样的事情,让我觉得它比它应该更复杂

SELECT *
FROM
 news
WHERE
 ( this = 45 || this= 0 )
AND
 active =  '1'
ORDER BY
 this ASC,
 date_added DESC
LIMIT 5

2 个答案:

答案 0 :(得分:2)

怎么样 -

SELECT *
FROM here
WHERE this < 5 -- added this WHERE clause based on the idea that there will be at least one item per this
ORDER BY this ASC, `date` ASC
LIMIT 5;

或者你是在五个结果之后再按日期排序 -

SELECT *
FROM (
    SELECT *
    FROM here
    WHERE this < 5 -- added this WHERE clause based on the idea that there will be at least one item per this
    ORDER BY this ASC, `date` ASC
    LIMIT 5
) AS tmp
ORDER BY `date` ASC

答案 1 :(得分:1)

您可以结合使用where子句和使用限制:

select * FROM here WHERE this = 1 OR this = 2 ORDER BY this LIMIT 5

即使在this等于1的15条记录中,这也只能带回5条记录......

相关问题