PostgreSQL 實現子查詢返回多行的案例
作為一個表達式使用的子查詢返回瞭多列:
在查詢中,我們需要以第2條查詢語句作為第一條查詢語句的條件,但是第一條根據這個條件查詢出來是多個數據,這時候又需要保留多個數據,運用子查詢就會報錯,
以下就為解決這種多對多關系查詢,且沒有關聯關系的表的解決方案:
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
SELECT film_id, title, rental_rate FROM film WHERE rental_rate > ( SELECT AVG (rental_rate) FROM film );
有瞭子查詢,在設定 需要查詢表才能得到 查詢條件時,就可以 直接 在一條語句中 寫,不用分開多條寫瞭,方便瞭許多。
子查詢返回多條時,可以在 where 子句中 用 IN,來匹配查詢條件。
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)
SELECT first_name, last_name FROM customer WHERE EXISTS ( SELECT 1 FROM payment WHERE payment.customer_id = customer.customer_id );
NO EXISTS ,與之相反,當子查詢返回0行時,返回true
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, 也就是返回所有行。
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 替換
子查詢 返回的 必須是 一列,
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:
x <> ANY (a,b,c)
is equivalent to
x <> a OR x <> b OR x <> c
ALL
所有子查詢返回的值 匹配 則 返回 true
也就是 大於最大,小於最小
SELECT film_id, title, length FROM film WHERE length > ALL ( SELECT ROUND(AVG (length),2) FROM film GROUP BY rating ) ORDER BY length;
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。如有錯誤或未考慮完全的地方,望不吝賜教。