MySQL은 where 절과 결합
조인하려는 두 개의 테이블이 있습니다.
categories 테이블의 모든 카테고리와 category_subscriptions 테이블의 사용자가 구독 한 모든 카테고리를 원합니다.
본질적으로 이것은 지금까지 내 쿼리입니다.
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
이것은 잘 작동하지만 쿼리 끝에 where 절을 추가하여 본질적으로 내부 / 동등 조인으로 만들고 싶습니다.
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
하나의 쿼리 만 사용하여 특정 사용자가 구독 한 모든 범주와 모든 범주를 얻으려면 어떻게해야합니까?
category_id는 범주 테이블과 user_category_subscriptions의 키입니다. user_category_subscriptions 테이블에 상주하는 user_id
감사
join
절이 아니라 절 에 넣어야 합니다 where
.
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON
user_category_subscriptions.category_id = categories.category_id
and user_category_subscriptions.user_id =1
inner join
를 사용하여 join
또는에 절을 넣는 것을 참조하십시오 where
. outer join
그러나을 사용하면 크게 다릅니다.
A와 join
조건, 당신은 당신이 테이블에 합류 할 것이라는 행 집합을 지정합니다. 즉 user_id = 1
, 먼저 평가 하고의의 하위 집합을 user_category_subscriptions
사용하여 user_id
의 1
모든 행에 조인합니다 categories
. 이렇게하면의 모든 행이 제공 categories
되는 반면 categories
이 특정 사용자가 구독 한 user_category_subscriptions
열만 정보가 표시됩니다. 물론 다른 모든 항목 은 열에 categories
채워집니다 .null
user_category_subscriptions
반대로, where
절은 조인을 수행 한 다음 행 집합 을 줄입니다. 따라서 이것은 모든 조인을 수행 한 다음 user_id
같지 않은 모든 행을 제거합니다 1
. 을 얻는 비효율적 인 방법이 남아 inner join
있습니다.
잘만되면 이것이 도움이된다!
이 시도
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
or user_category_subscriptions.user_id is null
참고 URL : https://stackoverflow.com/questions/1219909/mysql-join-with-where-clause
'IT박스' 카테고리의 다른 글
Firebase 메시징, 서버 키를 어디서 구할 수 있습니까? (0) | 2020.07.12 |
---|---|
ASP.NET의 문자열에서 HTML 태그를 어떻게 제거 할 수 있습니까? (0) | 2020.07.12 |
파일 또는 어셈블리 'System.Data.SQLite'를로드 할 수 없습니다 (0) | 2020.07.12 |
#define, enum 또는 const를 사용해야합니까? (0) | 2020.07.11 |
파이썬 'type'객체를 문자열로 변환 (0) | 2020.07.11 |