开发者

Query to return certain row always

Can you suggest a query where a condition will be executed always . Say :

if($country == 'hong-kong')
{
    $cond = "AND country = 'china'";
}

    $q = "
            SELECT 
                    *
            FROM
                tbl_people
            WHERE
                region = 'asia'
                $cond
            ORDER BY RAND()
            LIMIT 0,15      
    ";

Now suppose $country = 'hong-kong' and it has total 4 m开发者_Python百科embers . What I want to know is is there any way so that if $country = 'hong-kong' I wll have 15 members in result set including the 4 members from hong-kong ?


If I understand the question correctly, you want 15 random results from a larger set, but you want to be sure that all of the results matching country = 'hong-kong' are included in those 15.

I think you're going to want two queries, because the number of records returned by the first one (country = 'hong-kong') will dictate the limit you put on the second query. E.g.:

SELECT 
    *
FROM
    tbl_people
WHERE
    country = 'hong-kong'
ORDER BY RAND()
LIMIT 0,15      

Then

SELECT 
    *
FROM
    tbl_people
WHERE
    region = 'asia' AND country <> 'hong-kong'
ORDER BY RAND()
LIMIT 0,X

...where X is 15 - N, where N is how many rows were returned by your first query.

Then of course, you have to combine them in some kind of randomizing way (unless you want the Hong Kong results to be at the top/bottom/whatever of the list).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜