SQL連接、合並、子查詢


連接:連接分為內連接、外連接、交叉連接

內連接和外連接都是在笛卡爾積的基礎做一些修改。

合並查詢:把兩個相似的結果可以用union聯合起來。

mysql> select id,time from exam
    -> union
    -> select id,time from recuit;
+-----+------------+
| id  | time       |
+-----+------------+
|   1 | 2016-08-30 |
|   2 | 2016-09-10 |
|   8 | NULL       |
|   9 | 2016-08-31 |
| 100 | 2014-08-06 |
|   1 | 2016-08-31 |
|   2 | 2016-08-25 |
|   3 | 2016-08-31 |
+-----+------------+
8 rows in set (0.14 sec)

子查詢:

當子查詢為單行單列時:可以用子查詢的某條記錄作為where condition的元素之一。

mysql> select id from recuit
    -> where id>
    -> (select id from exam where name="tengxun");
+----+
| id |
+----+
|  2 |
|  3 |
|  9 |
+----+
3 rows in set (0.12 sec)

mysql> (select id from exam where name="tengxun");
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)

子查詢的返回值為多行多列時:

mysql> select * from recuit
    -> where (id,time)
    -> >
    -> (select id,time from exam where id=1);
+----+------------+-----------------+---------+--------+
| id | time       | process         | name    | result |
+----+------------+-----------------+---------+--------+
|  1 | 2016-08-31 | wait for result | baidu   |      1 |
|  2 | 2016-08-25 | haha            | tengxun |      1 |
|  3 | 2016-08-31 | jiayou          | wangyi  |      1 |
|  9 | 2016-08-31 | happy           | wangyi  |      1 |
+----+------------+-----------------+---------+--------+
4 rows in set (0.02 sec)

帶有關鍵字In的查詢,當主查詢的條件是子查詢的查詢結果中時,就可以通過關鍵字in來判斷。相反如果不是可以用not in。

select * from table_name
where field_name in
(select field_name from table_name);

帶有關鍵字ANY的查詢:

=ANY:功能與in一樣。

>ANY: 返回比子查詢中最小的還要大的記錄。只要大於子查詢中其中一個就行了。

<ANY:返回比子查詢中最大的還要小的記錄。只要小於一個就行了。

帶有關鍵字ALL的查詢:

>ALL:比最大的還要大。

<ALL:比最小的還要小。

帶有關鍵字exists

exist的子查詢實際上不返回任何記錄,而是返回true和false,如果子查詢存在至少一條記錄,就會返回true。否則就是false.

問題1:

 

--users表有1000條記錄,id自增,id都大於0

select * from users where exists (select * from users limit 0); --輸出多少條記錄?

select * from users where exists (select * from users where id < 0); --輸出多少條記錄?

答案(請選中查看):

10000條

0條

 原因:

exists查詢的本質,只要碰到有記錄,則返回true;所以limit根本就不會去管,或者說執行不到。

 

問題2:

exists可以完全代替in嗎?

不能。

例如:

--沒有關聯字段的情況:枚舉常量

select * from areas where id in (4, 5, 6);

--沒有關聯字段的情況:這樣exists對子查詢,要么全true,要么全false

select * from areas where id in (select city_id from deals where deals.name = 'xxx'); 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM