如何为SQL WHERE列IN编写关系代数?

时间:2016-08-30 09:31:50

标签: sql join relational-algebra sql-in

select age from person where name in (select name from eats where pizza="mushroom") 

我不知道该怎么写“in”。我该怎么解决这个问题?

3 个答案:

答案 0 :(得分:0)

在这种情况下,子选择等同于连接:

select age 
from person p, eats e
where p.name = e.name and pizza='mushroom'

所以你可以把它翻译成:

π age (person p⋈ p.name = e.name (σ pizza ='mushroom'(吃e)))

答案 1 :(得分:0)

这是我的猜测。我假设set membership symbol是关系代数的一部分

enter image description here

答案 2 :(得分:0)

For base table r, C a column of both r & s, and x an unused name,

select ... from r where C in s

returns the same value as

select ... from r natural join (s) x

The use of in requires that s has one column. The in is true for a row of r exactly when its C equals the value in s. So the where keeps exactly the rows of r whose C equals the value in s. We assumed that s has column C, so the where keeps exactly the rows of r whose C equals the C of the row in r. Those are same rows that are returned by the natural join.

(For an expression like this where-in with C not a column of both r and s then this translation is not applicable. Similarly, the reverse translation is only applicable under certain conditions.)

How useful this particular translation is to you or whether you could simplify it or must complexify it depends on what variants of SQL & "relational algebra" you are using, what limitations you have on input expressions and other translation decisions you have made. If you use very straightforward and general translations then the output is more complex but obviously correct. If you translate using a lot of special case rules and ad hoc simplifications along the way then the output is simpler but the justification that the answer is correct is longer.