MySQL查询多选随机结果

时间:2013-07-05 10:52:23

标签: php mysql sql select

我有一个查询,根据特定的县随机选择4个特色属性。

如果特定县有超过4个特色属性,则查询正确地拉出4 ...但是当县中少于4个时...我如何拉动县内的属性(如果找到的话)然后随机包括县外的记录,以便总共显示4个结果?

以下是我的查询示例...

SELECT
    `name`,
    `sleeps`,
    `town`,
    `county`,
    `price`,
    FLOOR(1 + RAND() * p.id) AS 'randnum'
FROM
    `properties_featured` AS `f` LEFT JOIN `properties` ON f.code=prop.code,
    (SELECT MAX(t.id) - 1 AS 'id' FROM `properties_featured` AS t) AS p
WHERE prop.status='on' AND `county`='Dorset'
ORDER BY `randnum` LIMIT 4;

非常感谢

1 个答案:

答案 0 :(得分:0)

WHERE子句中删除县匹配,并使其成为ORDER BY的一部分。

SELECT
    `name`,
    `sleeps`,
    `town`,
    `county`,
    `price`,
    FLOOR(1 + RAND() * p.id) AS 'randnum'
FROM
    `properties_featured` AS `f` LEFT JOIN `properties` ON f.code=prop.code,
    (SELECT MAX(t.id) - 1 AS 'id' FROM `properties_featured` AS t) AS p
WHERE prop.status='on'
ORDER BY `county` = 'Dorset' DESC, `randnum`
LIMIT 4;