我检查了类似的问题并尝试了依赖IN
或JOIN
的答案,但我无法理解。
我正在努力完成以下任务:
question_area
question_area
我有以下查询(我正在使用MySQL
5.6.17):
(SELECT question FROM question_active WHERE question_area = "B" AND
active_difficulty = 1 ORDER BY RAND() LIMIT 4)
UNION
(SELECT question FROM question_active WHERE question_area = "B" AND
active_difficulty = 2 ORDER BY RAND() LIMIT 3)
UNION
(SELECT question FROM question_active WHERE question_area = "B" AND
active_difficulty = 3 ORDER BY RAND() LIMIT 5)
我不知道它有多高效,但它确实有效。但是,我遇到两种情况:
PDO
类构建 clean 预处理语句,因为question_area
需要三个唯一参数标记,即使它具有相同的值。如manual中所述:
当您致电
PDOStatement::execute()
时,您必须为要传入语句的每个值添加唯一参数标记。
WHERE
条款,这些条款对于所有难度级别都是相同的。我的问题是,如何在不重复自己的情况下构建查询,以便我可以使用PDO
类。我只需要SQL
部分的帮助,而不是PHP。
我天真地希望有一种方法来构建单个查询并仅将LIMIT
应用于某些WHERE
子句。
我真的很感谢你的帮助。谢谢!
答案 0 :(得分:1)
$questions = [];
$sql = "SELECT question FROM question_active WHERE question_area = ?
AND active_difficulty = ? ORDER BY RAND() LIMIT ?";
$stmt = $pdo->prepare($sql);
foreach ([1,2,3] as $level)
{
$stmt->execute([$area, $level, $limit]);
$questions[$level] = $stmt->fetchAll();
}