1. 程式人生 > >mysql巢狀查詢

mysql巢狀查詢

3.使用Exist和Not Exist引數
這裡的Exist和Not Exist用途及用法和在其他沒有什麼大的區別,我就簡單舉幾個範例好了:

範例一:      SELECT DISTINCT store_type FROM Stores
                    WHERE EXISTS (SELECT * FROM Cities_Stores
                                  WHERE Cities_Stores.store_type = Stores.store_type);
範例二:   SELECT DISTINCT store_type FROM Stores
                       WHERE NOT EXISTS (SELECT * FROM Cities_Stores
                                   WHERE Cities_Stores.store_type = Stores.store_type);
範例三:  這個例子中巢狀使用了Not Exist語法,稍微注意一下:
               SELECT DISTINCT store_type FROM Stores S1
                    WHERE NOT EXISTS (
                               SELECT * FROM Cities WHERE NOT EXISTS (
                                       SELECT * FROM Cities_Stores
                                                 WHERE Cities_Stores.city = Cities.city
                                                         AND Cities_Stores.store_type = Stores.store_type));

4.條件關聯關係查詢:
解釋起來麻煩,直接看例子吧:
SELECT column1 FROM t1 AS x
     WHERE x.column1 = (SELECT column1 FROM t2 AS x
          WHERE x.column1 = (SELECT column1 FROM t3
               WHERE x.column2 = t3.column1));
跟其他資料庫做法是一樣的。

5.其他使用方法和注意:
除了上面這些還有很多很多,不過就不去細講了,因為這些跟別的資料庫差不多,只是為了給大家一個參考,提提就夠了。

         SELECT (SELECT s1 FROM t2) FROM t1;
         SELECT (SELECT s2 FROM t1);

支援子查詢的語法有:SELECT,INSERT,UPDATE,DELETE,SET和DO。

子查詢可以使用任何普通查詢中使用的關鍵詞:如DINSTINCT,GROUP BY,LIMIT,ORDER BY,UNION,ALL,UNION ALL等。可以使用<,>, <=, >=, =, <>運算子進行比較,也可以使用ANY ,IN和SOME進行集合的匹配。

轉載請註明出處:陳朋奕
http://www.blogjava.net/chenpengyi