作為一個表達式使用的子查詢返回了多列:
在查詢中,我們需要以第2條查詢語句作為第一條查詢語句的條件,但是第一條根據這個條件查詢出來是多個數據,這時候又需要保留多個數據,運用子查詢就會報錯,
以下就為解決這種多對多關系查詢,且沒有關聯關系的表的解決方案:
1
2
3
4
5
|
select c.rain_value,c.ad_nm from ( select *, json::json->t2.lon_lat as rain_value from actual_time_model_json t1, ( SELECT DISTINCT lon || '_' || lat as lon_lat,ad_nm from grid_all_points_null)t2 where section = '0' and t1.filename = 'Z_NWGD_C_BCCD_20180711022009_P_RFFC_SPCC-ER01_201807110800_02401.GRB2' )c where c.rain_value is not null |
補充:PostgreSQL 的子查詢 相關的知識 ,exists,any,all
Subquery
1
2
3
4
5
6
7
8
9
10
11
12
13
|
SELECT film_id, title, rental_rate FROM film WHERE rental_rate > ( SELECT AVG (rental_rate) FROM film ); |
有了子查詢,在設定 需要查詢表才能得到 查詢條件時,就可以 直接 在一條語句中 寫,不用分開多條寫了,方便了許多。
子查詢返回多條時,可以在 where 子句中 用 IN,來匹配查詢條件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
SELECT film_id, title FROM film WHERE film_id IN ( SELECT inventory.film_id FROM rental INNER JOIN inventory ON inventory.inventory_id = rental.inventory_id WHERE return_date BETWEEN '2005-05-29' AND '2005-05-30' ); |
EXISTS 操作符
在 where 子句的 查詢條件中,exists 操作符,會在子查詢有返回行時,返回true;不論返回幾行。
因此,子查詢中的查詢字段僅寫1就好;標準的寫法:EXISTS (SELECT 1 FROM tbl WHERE condition)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
SELECT first_name, last_name FROM customer WHERE EXISTS ( SELECT 1 FROM payment WHERE payment.customer_id = customer.customer_id ); |
NO EXISTS ,與之相反,當子查詢返回0行時,返回true
1
2
3
4
5
6
7
8
9
10
|
SELECT first_name, last_name FROM customer c WHERE NOT EXISTS ( SELECT 1 FROM payment p WHERE p.customer_id = c.customer_id AND amount > 11 ) ORDER BY first_name, last_name; |
當子查詢返回 NULL,會返回true, 也就是返回所有行。
1
2
3
4
5
6
7
8
9
10
|
SELECT first_name, last_name FROM customer WHERE EXISTS( SELECT NULL ) ORDER BY first_name, last_name; |
ANY
與任何子查詢返回的 值 匹配就 返回 true
expresion operator ANY(subquery)
表達式一般為 字段
操作符為 >,<,=,<>,>=,<=
ANY 可以與 SOME 替換
子查詢 返回的 必須是 一列,
1
2
3
4
5
6
7
|
SELECT title FROM film WHERE length >= ANY ( SELECT MAX ( length ) FROM film INNER JOIN film_category USING(film_id) GROUP BY category_id ); |
The = ANY is equivalent to IN operator.
Note that the <> ANY operator is different from NOT IN. The following expression:
1
|
x <> ANY (a,b,c) |
is equivalent to
1
|
x <> a OR x <> b OR x <> c |
ALL
所有子查詢返回的值 匹配 則 返回 true
也就是 大于最大,小于最小
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
SELECT film_id, title, length FROM film WHERE length > ALL ( SELECT ROUND( AVG (length),2) FROM film GROUP BY rating ) ORDER BY length; |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/Megamind_HL/article/details/108670357