简体   繁体   English

PHP / MySQL-从另一列等于值的列中选择RANDOM值

[英]PHP/MySQL - Select RANDOM value from column where another column equals value

I feel like my question is extremely basic and has been answered before but I just can't seem to find anything about it. 我觉得我的问题是非常基本的,之前已经回答过,但是似乎找不到任何东西。

Let's say I have a column named 'Names' and another called 'Level'. 假设我有一个名为“名称”的列,另一个名为“级别”。

-----------------------
 Names   |   Level
-----------------------
Scooby   |     3
Daphne   |     1
Shaggy   |     2
Fred     |     3
Velma    |     2
Scrappy  |     0

Basically I need a random name from the 'Names' column where 'Level' = 2. In this case randomly Shaggy or Velma. 基本上,我需要从“级别” = 2的“名称”列中获得一个随机名称。在这种情况下,将是随机的Shaggy或Velma。 In reality the database will probably be in the dozens if not hundreds of the same 'Level' value. 实际上,即使不是相同的“级别”值,数据库也可能只有几十个。

I've seen code using: 我看过使用以下代码:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

And I've tried playing with WHERE in there but with no success. 而且我尝试在那里玩WHERE,但没有成功。 Any ideas? 有任何想法吗? Using PHP to fetch the data from MySQL to return to a Flash file. 使用PHP从MySQL获取数据以返回Flash文件。 I apologize for the simplicity of the question. 对于这个问题的简单性,我深表歉意。

SELECT Names FROM table1
where Level = 2
ORDER BY RAND()
LIMIT 1

SQL Fiddle SQL小提琴

Have you tried this? 你有尝试过吗?

SELECT `Names` FROM `table_name`
WHERE `level` = 2
ORDER BY RAND()
LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM