1

我有一个查询,它根据特定县随机选择 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;

非常感谢

4

1 回答 1

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;
于 2013-07-05T11:00:56.820 回答