SQL,按RANDOM和LIMIT排序不起作用?

时间:2018-12-05 04:25:11

标签: sql

该查询为什么不停止在15点?这是我的查询。

SELECT title, type, profile
FROM playlists
WHERE active='1' AND feature='1' AND type='3' AND user='1'
ORDER BY RAND()
AND LIMIT 15

这会产生数十条记录,我每次只希望显示15个随机结果。我在俯视什么?

3 个答案:

答案 0 :(得分:2)

您需要删除关键字AND之前的LIMIT

$sql = "SELECT title, type, profile FROM playlists WHERE active='1' AND feature='1' AND type='3' AND user='1' ORDER BY RAND()  LIMIT 15";

答案 1 :(得分:2)

您可以尝试以下操作-您需要在AND之前删除LIMIT

SELECT title, type, profile FROM playlists WHERE active='1' AND feature='1' 
AND type='3' AND user='1' 
ORDER BY RAND() 
LIMIT 15

答案 2 :(得分:2)

此处是用于随机分配结果的有用链接。选中here

您的代码仅适用于MySQL。对于PostgreSQL和sqlite,请使用RANDOM()。对于SQL Server,请使用NEWID()。 对于PostgreSQL和sqlite

$sql = "SELECT title, type, profile FROM playlists WHERE active='1' AND feature='1' AND type='3' AND user='1' ORDER BY RANDOM() LIMIT 15";

对于SQl服务器

$sql = "SELECT title, type, profile FROM playlists WHERE active='1' AND feature='1' AND type='3' AND user='1' ORDER BY NEWID() FETCH NEXT 15 ROWS ONLY";

请注意SQL Server中限制的不同用法。有一个问题。 Link