mysql 或查詢

    想對一張表進行查詢,知足任意一個條件便可,能夠用union實現或查詢。 java

    

id
age
gender
1
20
female
2
21
male
3
22
male
    好比說person表中知足年齡超過20歲的女性或者年齡超過22歲的男性,才能夠結婚。咱們用if這樣寫
if(person.age > 22 || (person.age > 20 && person.gender == "female"){
    System.out.println("達到法定要求准許結婚!");
}
怎麼樣翻譯成mysql語句呢,用union
select * from person p where p.age > 22
union select * from person p where p.age >20 and p.gender = "female";
注意:這裏使用的是union不是union all,由於第二句查詢的結果集裏也會包涵第一句查詢的結果集,使用union,則返回的行都是惟一的,如同您已經對整個結果集合使用了distinct,使用union all則不會排重返回全部的行。

若是您想使用ORDER BY或LIMIT子句來對所有UNION結果進行分類或限制,則應對單個地SELECT語句加圓括號,並把ORDER BY或LIMIT放到最後一個的後面: mysql

(select * from person p where p.age > 22)
union 
(select * from person p where p.age >20 and p.gender = "female")
order by age limit 10;

怎樣統計union以後的記錄條數呢,天然會想到這個 sql

select count (*) from
(select * from person p where p.age > 22
union select * from person p where p.age >20 and p.gender = "female");
結果不行,後來查網上有說這樣寫的


select sum (cnt) from
(select count(*) as cnt from person p where p.age > 22
union select count(*) as cnt from person p where p.age >20 and p.gender = "female");

結果仍是不行,都會報「Every derived table must have its own alias」這個錯誤,百度一下 spa

由於,進行嵌套查詢的時候子查詢出來的的結果是做爲一個派生表來進行上一級的查詢的,因此子查詢的結果必需要有一個別名。 翻譯

select count (*) from
(select * from person p where p.age > 22
union select * from person p where p.age >20 and p.gender = "female")as total;
select sum (cnt) from
(select count(*) as cnt from person p where p.age > 22
union select count(*) as cnt from person p where p.age >20 and p.gender = "female") as total;
相關文章
相關標籤/搜索