编辑表结构,http://puu.sh/bQKRz/785c731604.png
/*
* Let's get a RANDOM question from the questions table
* Ignore questions the group has already
*/
Group.prototype.getRandomQuestion = function(callback){
var self = this;
var answered = this.answered.join();
var categories = this.categories;
var sql = "SELECT * FROM `questions` WHERE (`id` NOT IN (?) AND `category` IN (?)) ORDER BY RAND() LIMIT 1";
this.mysql_pool.getConnection(function(err, conn){
if(!err){
conn.query(sql, [answered, categories], function(err, r){
conn.release();
以上是我的代码。由于某些该死的原因,它在SHOULDN' T时始终从数据库中取出至少一个结果。不应该满足where子句。
我打开了PhpMyAdmin,使用插入其中的相同确切数据运行相同的确切查询。它返回空了。好。那么为什么这个代码块也没空呢?
以下是answered
和categories
的值:
answered
=" 1,2"
categories
=" 1,2,3,4"
在我的questions
表格中,只有两个问题。这两个问题都有ID 1
& 2
。那么,为什么这段代码仍然会返回一行呢?
答案 0 :(得分:2)
假设我们有一个表,其中包含两行,分别为id 1和2。
select * from table where id in ('1, 2')
==>您将只获得一行ID为 1
select * from table where id not in ('1, 2')
==>您还将只获得一行ID为 2
要点是(' 1,2')与(' 1',' 2&#39)不一样;)强>
答案 1 :(得分:0)
您可以使用返回ID 2的数组提供完整的SQL吗?抱歉把它作为答案......不允许我发表评论。
答案 2 :(得分:0)
var ID = new Array(1,2);
var Categories = new Array(1,2,3,4,5);
var IDstring = "'" + ID.join("','") + "'";
var Categoriesstring = "'" + Categories.join("','") + "'";
var sql = "SELECT * FROM `questions` WHERE `id` NOT IN (" + IDstring + ") AND `category` IN (" + Categoriesstring + ") ORDER BY RAND() LIMIT 1";