0

我想将具有 where not in 子句的 sql 查询转换为元组关系演算。Existential 和 Universal 量词仅实现 where exists 和 where not exists 子句,所以我想知道如何实现 where not in?

我的表是serves(bar,beer),frequents(drinker,bar),likes(drinker,beer)。以下查询选择只经常光顾提供他们喜欢的啤酒的酒吧的饮酒者。

select distinct f2.drinker from frequents f2 where f2.drinker not in (select f1.drinker from frequents f1 where (f1.bar,f1.drinker) not in (select f.bar,f.drinker from frequents f,serves s,likes l where l.beer=s.beer and f.bar=s.bar and f.drinker=l.drinker))

如果有人可以解释我如何在 TRC 中实现不需要转换整个查询就足够了。我正在使用http://www-rohan.sdsu.edu/~eckberg/relationalcalculusemulator.html
来检查我的关系演算和将其转换为 sql 查询。

笔记:

如果您在查询中使用含义。

它不支持蕴涵。例如蕴涵可以实现如下。(p==>q) 可以写成 (not p or q) 形式,因为两者在逻辑上是等价的。

4

3 回答 3

0

Your query is equal your inner query my friend,because you said f2 is something which is not in f1 and f1 is something which is not in f and all of them got one source frequents and it means f2=f and your query returns this:

select f.bar,f.drinker from frequents f,serves s,likes l 
where l.beer=s.beer and f.bar=s.bar and f.drinker=l.drinker;

but i think this query can give you better results my friend:

select f.bar,f.drinker from frequents f 
left outer join serves s on  f.bar=s.bar 
left outer join likes l on l.beer=s.beer and f.drinker=l.drinker;

Tack a look at SQL Fiddle, it will help you to get it better.

于 2014-03-10T06:15:27.373 回答
0

那么你所描述的是WHERE NOT EXISTS(subquery)

http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html

如果那不是你想要的,请告诉我。


还有为什么你不把你的陈述的逻辑从

WHERE drinker NOT IN (drinker) 到 WHERE IN(drinker=null)

INITIAL QUERY .. 已格式化,因此更易于阅读

SELECT 
    DISTINCT f2.drinker 
FROM frequents f2 
WHERE f2.drinker NOT IN 
    (
        SELECT 
            f1.drinker 
        FROM frequents f1 
        WHERE (f1.bar,f1.drinker) NOT IN 
        (
            SELECT 
                f.bar,
                f.drinker 
            FROM frequents f,
                serves s,
                likes l 
            WHERE l.beer=s.beer AND f.bar=s.bar AND f.drinker=l.drinker
        )
    )

你应该能做的是这个

SELECT 
    DISTINCT f2.drinker 
FROM frequents f2 
WHERE f2.drinker IN 
    (
        SELECT 
            f1.drinker 
        FROM frequents f1 
        WHERE f1.drinker IS NULL AND (f1.bar,f1.drinker) IN 
        (
            SELECT 
                f.bar,
                f.drinker 
            FROM frequents f,
                serves s,
                likes l 
            WHERE l.beer=s.beer AND f.bar=s.bar AND f.drinker=l.drinker AND f.drinker IS NULL
        )
    )

希望这有效,我无法真正测试它。但这个想法不是说where this is not in thissay where this is in this where id (in subquery) is null

于 2014-03-10T04:56:24.180 回答
0

我用 where exists 和 where not exists 重写了我的查询,现在很容易将其转换为关系演算。答案是

{T.drinker|∃f2Єfrequents (∀f1Єfrequents (∃fЄfrequents(∃sЄserves ∃lЄlikes(s.beer=l.beer^l.drinker=f.drinker^s.bar=f.bar^f1.drinker=f.drinker^f.bar=f1.bar^f2.bar=f1.bar v f2.drinker≠f1.drinker)))}

无论如何,感谢您的投入。

于 2014-03-10T19:51:09.610 回答