问题
I am trying to design a query with OR and NAND operation, Can some one let me know Is the query is correct:
Question 1: Is this query correct?
select * from country where country_code='AL' UNION (SELECT * from country
WHERE country_id NOT IN
(SELECT country_id from country
where country_name='Land islands'
UNION
SELECT country_id from country
where country_code='AX'
));
I created the query with the help of my another question of mine;
Ref:
Question 2:
I want to use 5 query with AND,NOT,NAND,OR operation in between them. I created up to 3 (Check my Question 1) I need help for creating 5 Select Queries.
My Application is search application where the user can search the database with i5 query block in between each block we have operations like below I mentioned. But the operations are carried out in one single table.
Explanation:
I want to select records inside a table and I will use many operations in between the table. MAX 5 operation in side a query.
Query 1,Query 2, Query 3, Query 4, Query 5.
Cases:
(Query 1 AND Query 2 OR Query 3 NAND Query 4 NOT Query 5)
(Query 1 OR Query 2 OR Query 3 OR Query 4 OR Query 5)
(Query 1 AND Query 2 AND Query 3 AND Query 4 AND Query 5)
(Query 1 NOT Query 2 NOT Query 3 NOT Query 4 NOT Query 5)
etc.. The operation in between the query Block may vary... I will write my PHP script according to that but I want to perform the Logic in such a way that I can join each logic..
Now I need an help
回答1:
Why you are using the UNION
in between same Table
. You may easily complete this query by using operators
like
Select * from country where country_code='AL' or (country_name <> 'Land islands' and country_code <> 'AX');
Hope it works for you.
回答2:
The simplest way to write your first query:
select *
from country
where country_code='AL' and country_name not in ('Land islands', 'AX')
This works under the assumption that country_id
is unique in the country
table -- a reasonable assumption based on the naming. If this is not the case, the query would be a bit more complicated.
Your original query requires multiple scans of the table, an anti-join for the NOT IN
with a subquery, and aggregation to remove duplicates (it has union
instead of union all
).
The revised version just scans the table, keeping the rows that match the where
clause.
Based on your first query, you can do everything you want just by using AND
and OR
(and perhaps IN
and NOT IN
) in a where
clause.
来源:https://stackoverflow.com/questions/16940484/select-query-with-or-and-nand