我在SQLite3数据库中具有下表:
CREATE TABLE overlap_results ( neighbors_of_annotation varchar(20), other_annotation varchar(20), set1_size INTEGER, set2_size INTEGER, jaccard REAL, p_value REAL, bh_corrected_p_value REAL, PRIMARY KEY (neighbors_of_annotation, other_annotation) );
我想执行以下查询:
SELECT * FROM overlap_results WHERE (neighbors_of_annotation, other_annotation) IN (('16070', '8150'), ('16070', '44697'));
也就是说,我有几个批注ID的元组,我想获取每个这些元组的记录。sqlite3提示给我以下错误:
SQL error: near ",": syntax error
如何正确将其表示为SQL语句?
编辑 我意识到我并没有很好地解释我真正的追求。让我再尝试一下。
如果一个人给我neighbors_of_annotation他们感兴趣的任意术语列表,我可以编写如下的SQL语句:
neighbors_of_annotation
SELECT * FROM overlap_results WHERE neighbors_of_annotation IN (TERM_1, TERM_2, ..., TERM_N);
但现在假设这个人想给我双方面的,如果形式(TERM_1,1, TERM_1,2),(TERM_2,1, TERM_2,2),… (TERM_N,1, TERM_N,2),这里TERM_i,1是neighbors_of_annotation和TERM_i,2是other_annotation。SQL语言是否提供同样优雅的方法来为感兴趣的对(元组)制定查询?
(TERM_1,1, TERM_1,2)
(TERM_2,1, TERM_2,2)
(TERM_N,1, TERM_N,2)
TERM_i,1
TERM_i,2
other_annotation
最简单的解决方案似乎是为这些对创建一个新表,然后将该表与要查询的表连接起来,并仅选择第一项和第二项匹配的行。创建大量AND / OR语句看起来很可怕,而且容易出错。
AND / OR
我从未见过这样的SQL。如果存在,我会怀疑它是非标准扩展。尝试:
SELECT * FROM overlap_results WHERE neighbors_of_annotation = '16070' AND other_annotation = '8150' UNION ALL SELECT * FROM overlap_results WHERE neighbors_of_annotation = '16070' AND other_annotation = '44697';
换句话说,从元组构建动态查询,但以一系列的并集或在OR中的一系列AND的形式构建动态查询:
SELECT * FROM overlap_results WHERE (neighbors_of_annotation = '16070' AND other_annotation = '8150') OR (neighbors_of_annotation = '16070' AND other_annotation = '44697');
因此,代替代码(伪代码,仅在我的脑海中进行测试,因此调试是您的责任),例如:
query = "SELECT * FROM overlap_results" query += " WHERE (neighbors_of_annotation, other_annotation) IN (" sep = "" for element in list: query += sep + "('" + element.noa + "','" + element.oa + "')" sep = "," query += ");"
相反,您会得到类似以下内容的信息:
query = "SELECT * FROM overlap_results " sep = "WHERE " for element in list: query += sep + "(neighbors_of_annotation = '" + element.noa + "'" query += " AND other_annotation = '" + element.oa + "')" sep = "OR " query += ";"