简体   繁体   中英

How can I know a where-clause query results contains another where-clause query results?

How can I know a where-clause's query-results contains another where-clause's query-results? For example:

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

Sorry,My English proficiency is very bad.

There is a table: Countries(id,name).

id      name
0       America
1       China
2       Japan
3       England

Obviously,The query-results of select id, name from Countries where id>0 contains select id, name from Countries id>2 's. I want to get the result by comparing the two where-clauses directly, I don't want to execute the actual query operation

I use java.

It depends on your data, so you have to run each where clauses by joining their results. You can join them and check if any result exists.

You can use set operators to compare the two. If query2 does not have any rows that aren't in query1, than query1 contains query2.

Eg, for Oracle:

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

For MS SQL Server and PostgreSQL, use EXCEPT instead of MINUS .

Well, first of all, you'd need a way to represent your condition other than just text. Without fleshing out all of the classes, below should get the gist of it.

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
    }
}

And so on. Comparing strings and coming up with other conditions is left as an exercise to the OP (or the reader, if the reader is inclined to do so).


Of course, this works up to a point. As soon as you want to answer questions that depend on the data, you have no choice but to execute some query. For instance, there is easier way to find out that WHERE id > 1 contains WHERE name > 'China' than issueing the queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM