문제

가입하고 싶은 테이블 두 개가 있습니다.

카테고리 테이블의 모든 카테고리와 카테고리 _subscriptions 테이블의 사용자가 구독 한 모든 범주를 원합니다.

본질적으로 이것은 지금까지 내 쿼리입니다.

SELECT *
FROM categories
LEFT JOIN user_category_subscriptions 
     ON user_category_subscriptions.category_id = categories.category_id

이것은 제대로 작동하지만 쿼리 끝에 WHERE 절을 추가하고 본질적으로 내부/EQUI 조인이됩니다.

   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_id user_id user_category_subscriptions 테이블에 있습니다.

감사해요

도움이 되었습니까?

해결책

당신은 그것을 넣어야합니다 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 a user_id1 모든 행에 합류합니다 categories. 이것은 당신에게 모든 행을 줄 것입니다 categories, 단지 categories 이 특정 사용자가 가입 한 것은 user_category_subscriptions 열. 물론, 다른 모든 것 categories 함께 채워질 것입니다 null 에서 user_category_subscriptions 열.

반대로, a 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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top