2013-07-05 133 views
1

我有一個查詢,隨機選擇4個基於特定縣的特色屬性。MySQL查詢多選隨機結果

如果某個特定縣的特色屬性超過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; 

非常感謝

回答

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; 
+0

偉大,感謝@Barmar工作正常:) –