从字符串中的ID中检索表中的随机行

时间:2013-11-28 09:31:13

标签: php mysql

我正在尝试从我的表中选择一个随机行,其中包含我的数组中的ID。

字符串$ data包含我想用逗号分隔的所有id列表。

$statement = $conn->prepare("SELECT * FROM clients ORDER BY rand() WHERE find_in_set(id,'$data') LIMIT 1");

这是我的查询,

id是我桌子的字段。

这是错误

An error has occurred exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE find_in_set(id,'0,1') LIMIT 1' at line 1' in 

3 个答案:

答案 0 :(得分:1)

试试这个,ORDER BY应该在where条件之后或tablename

SELECT * FROM clients  WHERE find_in_set(id,'$data') ORDER BY rand() LIMIT 1

语法:http://dev.mysql.com/doc/refman/5.0/en/select.html

 SELECT
[ALL | DISTINCT | DISTINCTROW ]
  [HIGH_PRIORITY]
  [STRAIGHT_JOIN]
  [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
  [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
select_expr [, select_expr ...]
[FROM table_references
[WHERE where_condition]
[GROUP BY {col_name | expr | position}
  [ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {col_name | expr | position}
  [ASC | DESC], ...]
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
[PROCEDURE procedure_name(argument_list)]
[INTO OUTFILE 'file_name' export_options
  | INTO DUMPFILE 'file_name'
  | INTO var_name [, var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]

答案 1 :(得分:0)

您的查询错误。你需要先重写它。见下文

$statement = $conn->prepare("SELECT * FROM clients WHERE find_in_set(id,'$data') ORDER BY rand() LIMIT 1");

答案 2 :(得分:0)

您的查询中的order by子句放置错误。

$statement = $conn->prepare("SELECT * FROM clients WHERE find_in_set(id,'$data')
ORDER BY rand() LIMIT 1");