我有两张大桌子:
products
--------
id (char) (primary key)
somefield1 (char)
somefield2 (char)
和
expired_products
------
id (char) (primary key)
我想只有那些产品中但未过期的ID(id不在expired_products中)。在MS Access中我会做这样的事情
SELECT products.*
FROM products LEFT JOIN expired_products ON products.id = expired_products.id
WHERE expired_products.id Is Null;
最终,我想将查询结果写入新表。
SQL Server Compact(sdf文件)中是否有更好的(更快的查询)解决方案?
顺便说一下。我正在使用C#并使用SqlCeConnection访问数据库。
答案 0 :(得分:4)
标准SQL和SQL Server中的减号运算符为EXCEPT
:
SELECT id
FROM products
EXCEPT
SELECT id
FROM expired_products;
...但似乎Compact 4.0中不支持EXCEPT
:(
与SQL一样,这是执行semi difference的替代方式:
e.g。 NOT EXISTS
SELECT *
FROM products AS p
WHERE NOT EXISTS (
SELECT *
FROM expired_products AS e
WHERE p.id = e.id
);
e.g。 NOT IN
SELECT *
FROM products
WHERE id NOT IN (SELECT id FROM expired_products);
答案 1 :(得分:2)
create table new_table (
id char(7) -- same as primary key in products
)
这是在C#中执行的命令,它是“insert into ... select ...”语句:
insert into new_table (id)
select p.id
from products p
where not exists (select 1 from expired_products e.id = p.id)
评论后添加:
INSERT (SQL Server Compact) on MSDN
INSERT [INTO]
table_name [ ( column_list ) ]
{ VALUES
( { DEFAULT | NULL | expression } [ ,...n] )
| derived_table
}
来自MSDN:
derived_table 的
任何有效的 SELECT 语句,它返回要插入表中的数据行。