问题描述
假设我有两个表A{int m}和B{int m},我必须在使用关系代数的两个表中找到最大的 m 使用加入我们可以做到,但我不确定我的猜测是否正确.
注意:这是一个面试问题.
推荐答案
嗯,我很困惑这个问题为什么涉及两张表.对于问的问题,我只会将两者结合(如Stilescrisis所做的那样),然后解决一个桌子.
so:如何仅使用natjoin在表中找到最大m?这是在表上找到层次结构的表上的顶级节点的简化版本(想想汇编/组件爆炸或组织图).
关键想法是,我们需要将表"复制"到具有不同属性名称的东西中,以便我们可以对元组进行比较. (因此,这将使用natjoin aka交叉产品的退化形式).请参阅此处的示例如何找到具有关系代数的最大值?
A NOT MATCHING ((A x (A RENAME m AS mm)) WHERE m < mm)
亚trahend的所有元素都比其他一些元组少.反加入除外的所有元组 - 即最大. (我认为使用不匹配比负相比更易于理解,并且不需要关系与工会兼容.它大致相当于不存在SQL)
[我已经使用了教程D语法,以避免用希腊字母弄乱.]
其他推荐答案
SELECT M FROM (SELECT M FROM A UNION SELECT M FROM B) ORDER BY M DESC LIMIT 1
这不使用MAX,只是普通的香草SQL.
问题描述
Suppose I have two tables A{int m} and B{int m} and I have to find maximum m among two tables using relational algebra but I cannot use max function.How can I do it?I think using join we can do it but i am not sure if my guess is correct or not.
Note: this is an interview question.
推荐答案
Hmm, I'm puzzled why the question involves two tables. For the question as asked, I would just UNION the two (as StilesCrisis has done), then solve for a single table.
So: how to find the maximum m in a table using only NatJOIN? This is a simplified version of finding the top node on a table that holds a hierarchy (think assembly/component explosions or org charts).
The key idea is that we need to 'copy' the table into something with a different attribute name so that we can compare the tuples pair-wise. (And this will therefore use the degenerate form of NatJOIN aka cross-product). See example here How can I find MAX with relational algebra?
A NOT MATCHING ((A x (A RENAME m AS mm)) WHERE m < mm)
The subtrahend is all tuples with m less than some other tuples. The anti-join is all the tuples except those -- ie the MAX. (Using NOT MATCHING I think is both more understandable than MINUS, and doesn't need the relations to be UNION-compatible. It's roughly equivalent to SQL NOT EXISTS).)
[I've used Tutorial D syntax, to avoid mucking about with greek letters.]
其他推荐答案
SELECT M FROM (SELECT M FROM A UNION SELECT M FROM B) ORDER BY M DESC LIMIT 1
This doesn't use MAX, just plain vanilla SQL.