itsource

SQL은 1 x N 중에서 선택할 수 있으며, 모든 크기가

mycopycode 2023. 1. 8. 14:40
반응형

SQL은 1 x N 중에서 선택할 수 있으며, 모든 크기가

테이블이 있어요.books그리고.bookType1XN의 관계를 나타내고 있습니다.

books

+-----+------------------+----------+-------+
| id  |      title       | bookType | price |
+-----+------------------+----------+-------+
|   1 | Wizard of Oz     |        3 |    14 |
|   2 | Huckleberry Finn |        1 |    16 |
|   3 | Harry Potter     |        2 |    25 |
|   4 | Moby Dick        |        2 |    11 |
+-----+------------------+----------+-------+

bookTypes

+-----+----------+
| id  |   name   |
+-----+----------+
|   1 | Fiction  |
|   2 | Drama    |
|   3 | Children |
+-----+----------+

책을 가져오려면 어떻게 해야 하나요?모든 책이 12($)보다 비싼 유형이 경우 예상되는 출력은 다음과 같습니다.

+-----+----------+
| id  |   name   |
+-----+----------+
|   1 | Fiction  |
|   3 | Children |
+-----+----------+

사용할 수 있습니다.not exists:

select t.*
from bookTypes t
where not exists (
    select 1
    from books b
    where b.bookType = t.id and b.price < 12
)

하나 이상의 관련 책이 있는 책 유형을 선택하려면:

select t.*
from bookTypes t
where 
    exists (select 1 from books b where b.bookType = t.id)
    and not exists (select 1 from books b where b.bookType = t.id and b.price < 12)

을 실행합니다.GROUP BY,사용하다HAVING최저가격이 12 이상인 북타입만 반환한다.

SELECT bt.name
FROM bookTypes bt
INNER JOIN books b ON b.bookType = bt.id
group by bt.name
HAVING SUM(b.price <= 12) = 0;

직접 사용할 수 있습니다.having min(price) >= 12로 묶어서bookType

select t.id, t.name
  from bookTypes t
  join books b
    on t.id = b.bookType
 group by b.bookType   
 having min(price) >= 12

또한 DB 버전이 적어도10.2, 그 후 몇 가지 기능을 사용할 수도 있습니다.window functions같은 분석 질문의 경우min(..) over (partition by .. order by ..):

with t as
(
select t.id, t.name, min(price) over (partition by bookType) as price
  from bookTypes t
  join books b
    on t.id = b.bookType
)
select id, name 
  from t
 where price >= 12 

그 안에서min() over (..)윈도 함수는 다음을 사용하여 각 책 종류에 대한 최소 가격을 결정합니다.partition by bookType

Demo

저는 GMB의 솔루션이 지금까지의 솔루션 중 최고라고 생각합니다.그러나 완벽성을 위해:를 사용할 수도 있습니다.ALL연산자(상관된 서브쿼리 포함)입니다.그게 아마 가장 간단한 해결책일 겁니다.

SELECT *
       FROM booktypes bt
       WHERE 12 < ALL (SELECT b.price
                              FROM books b
                              WHERE b.booktype = bt.id);

그냥 책 중에서 이너조인트북을 고르면 안 돼요?ID WHERE 가격 > 12?

SELECT bt.*
FROM bookTypes bt
INNER JOIN books b ON b.bookType = bt.id
WHERE b.price > 12

언급URL : https://stackoverflow.com/questions/59032792/sql-select-from-1-x-n-where-all-bigger-than

반응형