1

我在将关系代数转换为这个相当复杂的查询的 SQL 时遇到问题:

我需要从连接到表 B 的表 A 中选择所有值,其中表 B 中没有匹配的记录,或者有匹配的记录,但匹配的记录集没有包含可能 8 个总值中的 4 个的字段.

数据库是 MySQL 5.0... 使用 InnoDB 引擎作为表。

4

3 回答 3

3
Select 
  a.* 
from 
  a 
left join 
  b 
on 
  a.id=b.id 
where 
  b.id is null 
or 
  b.field1 not in ("value1","value2","value3","value4");
于 2012-07-11T00:13:31.693 回答
1

我不确定是否有任何真正的性能改进,但另一种方法是:

SELECT 
    *
FROM
    tableA
WHERE
    id NOT IN ( SELECT id FROM tableB WHERE field1 NOT IN ("value1", "value2"));
于 2012-07-11T00:21:35.963 回答
0

你的要求有点不清楚。我的第一种解释是你只想要 A 列,并且永远不要超过给定 A 行的 1 个实例。

select * from A where not exists (
  select B.id 
    from B 
   where B.id=A.id 
     and B.field in ('badVal1','badVal2','badVal3','badVal4')
)

我的第二种解释是,您希望(A 外连接到 B)中的所有列,如果有多个 B 行,则可能有多个 A 行的实例,只要不存在具有禁止值的 B 行。

select * from A
  left outer join B on A.id=B.id
 where not exists (
               select C.id
                 from B as C
                where A.id=C.id
                  and C.field in ('badVal1','badVal2','badVal3','badVal4')
           )

两个查询都可以用 NOT IN 代替相关的 NOT EXISTS 来表示。在不知道数据的情况下很难知道哪个会更快。

于 2012-07-11T01:44:10.697 回答