我怎么知道where子句查询结果包含另一个where子句查询结果?

时间:2013-11-18 07:59:20

标签: java sql

我怎么知道where子句的查询结果包含另一个where子句的查询结果? 例如:

"id>0" contains "id>1"
"id>0 or name='China'" contains "id>1"
"id>0 or name='China'" contains "name='China'"

抱歉,我的英语水平很差。

有一张表:国家(身份证,姓名)。

id      name
0       America
1       China
2       Japan
3       England

显然,select id, name from Countries where id>0的查询结果包含select id, name from Countries id>2。 我想通过直接比较两个where子句得到结果,我不想执行实际的查询操作

我使用java。

3 个答案:

答案 0 :(得分:0)

这取决于您的数据,因此您必须通过加入其结果来运行每个where子句。您可以加入它们并检查是否存在任何结果。

答案 1 :(得分:0)

您可以使用set运算符来比较两者。如果query2没有任何不在query1中的行,则query1包含query2。

例如,对于Oracle:

SELECT *
FROM   my_table
WHERE  condtion2
MINUS
SELECT *
FROM   my_table
WHERE  condtion1

对于MS SQL Server和PostgreSQL,请使用EXCEPT代替MINUS

答案 2 :(得分:0)

嗯,首先,您需要一种方法来表示您的条件其他而不仅仅是文本。如果没有充实所有课程,下面应该得到它的要点。

public abstract class Condition implements Comparable<C extends Condition> {
    public abstract boolean equals(C other);
    public abstract boolean contains(C other);
};

public class OrCondition extends Condition {
    // contains a list of the conditions it's OR-ring together

    public boolean contains(Condition other) {
        // true if the list of conditions 
        // contains a condition c such that c.equals(other)
    }
}

public class GreaterThanCondition extends Condition {
    // contains a fieldname and a number to compare it to

    public boolean contains(Condition other) {
        // true if other is a GreaterThanCondition as well
        // on the same field and the number other.number >= this.number
    }
}

等等。比较字符串和提出其他条件留给OP(或读者,如果读者倾向于这样做)的练习。


当然,这很有用。只要您想回答依赖于数据的问题,您就别无选择,只能执行某些查询。例如,有更简单的方法可以找出WHERE id > 1包含WHERE name > 'China'而不是发出查询。

相关问题