作為一個(gè)表達(dá)式使用的子查詢返回了多列:
在查詢中,我們需要以第2條查詢語句作為第一條查詢語句的條件,但是第一條根據(jù)這個(gè)條件查詢出來是多個(gè)數(shù)據(jù),這時(shí)候又需要保留多個(gè)數(shù)據(jù),運(yùn)用子查詢就會(huì)報(bào)錯(cuò),
以下就為解決這種多對(duì)多關(guān)系查詢,且沒有關(guān)聯(lián)關(guān)系的表的解決方案:
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
補(bǔ)充:PostgreSQL 的子查詢 相關(guān)的知識(shí) ,exists,any,all
Subquery
SELECT
film_id,
title,
rental_rate
FROM
film
WHERE
rental_rate > (
SELECT
AVG (rental_rate)
FROM
film
);
有了子查詢,在設(shè)定 需要查詢表才能得到 查詢條件時(shí),就可以 直接 在一條語句中 寫,不用分開多條寫了,方便了許多。
子查詢返回多條時(shí),可以在 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 操作符,會(huì)在子查詢有返回行時(shí),返回true;不論返回幾行。
因此,子查詢中的查詢字段僅寫1就好;標(biāo)準(zhǔn)的寫法: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 ,與之相反,當(dāng)子查詢返回0行時(shí),返回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;
當(dāng)子查詢返回 NULL,會(huì)返回true, 也就是返回所有行。
SELECT
first_name,
last_name
FROM
customer
WHERE
EXISTS( SELECT NULL )
ORDER BY
first_name,
last_name;
ANY
與任何子查詢返回的 值 匹配就 返回 true
expresion operator ANY(subquery)
表達(dá)式一般為 字段
操作符為 >,<,=,<>,>=,<=
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:
1x <> ANY (a,b,c)
is equivalent to
1x <> 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;
文章來源:腳本之家
來源地址:https://www.jb51.net/article/204611.htm
申請(qǐng)創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!