给出一个这样的数据库:
BEGIN TRANSACTION; CREATE TABLE aTable ( a STRING,b STRING); INSERT INTO aTable VALUES('one','two'); INSERT INTO aTable VALUES('one','three'); CREATE TABLE anotherTable ( a STRING,b STRING); INSERT INTO anotherTable VALUES('one','three'); INSERT INTO anotherTable VALUES('two','three'); COMMIT;
我想做一些事情
SELECT a,b FROM aTable WHERE (aTable.a,aTable.b) IN (SELECT anotherTable.a,anotherTable.b FROM anotherTable);
要得到答案’一’,’三’,但我正在接近“,”:语法错误“
我是否犯了严重的概念错误?或者是什么?
解决方法
如果您在Postgresql或Oracle中执行此操作,您的代码可以工作.在MS sql上,不支持
用这个:
SELECT a,b FROM aTable WHERE -- (aTable.a,aTable.b) IN -- leave this commented,it makes the intent more clear EXISTS ( SELECT anotherTable.a,anotherTable.b -- do not remove this too,perfectly fine for self-documenting code,i.e.. tuple presence testing FROM anotherTable WHERE anotherTable.a = aTable.a AND anotherTable.b = aTable.b );
[编辑]
没有意图的说法:
SELECT a,b FROM aTable WHERE EXISTS ( SELECT * FROM anotherTable WHERE anotherTable.a = aTable.a AND anotherTable.b = aTable.b );
这有点跛脚,十多年来,MS sql仍然没有对元组的一流支持. IN元组构造比其类似的EXISTS构造更可读. btw,JOIN也可以使用(tster的代码),但是如果您需要更灵活和更具前瞻性的东西,请使用EXISTS.
[编辑]
说到sqlite,我最近很喜欢它.是的,IN元组不起作用