6

我在 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 语句:

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), where TERM_i,1is inneighbors_of_annotationTERM_i,2is in other_annotation。SQL 语言是否提供了一种同样优雅的方式来为感兴趣的对(元组)制定查询?

最简单的解决方案似乎是为这些对创建一个新表,然后将该表与要查询的表连接起来,并仅选择第一个词和第二个词匹配的行。创建大量AND / OR语句看起来很可怕且容易出错。

4

2 回答 2

4

我从未见过这样的 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 += ";"
于 2010-04-08T01:31:10.803 回答
2

我不知道有任何 SQL 方言支持 IN 子句中的元组。我认为你被困在:

SELECT * FROM overlap_results WHERE (neighbors_of_annotation = '16070' and other_annotation = '8150') or (neighbors_of_annotation = '16070' and other_annotation = '44697')

当然,这个特定的查询可以简化为:

SELECT * FROM overlap_results WHERE neighbors_of_annotation = '16070' and (other_annotation = '8150' or other_annotation = '44697')

通常 SQL WHERE 子句谓词只允许过滤单列。

于 2010-04-08T01:31:55.083 回答