아래와 같은 쿼리를 사용하면 ID의 색상이 파란색, 보라색, 녹색, 흰색 및 검은 색 인 행을 가져올 수 있습니다.mysql cross join에 있지 않습니까?
SELECT t1.id, col
FROM extra as e INNER JOIN your_table as t1 USING (id)
CROSS JOIN your_table as t2 USING (id)
CROSS JOIN your_table as t3 USING (id)
CROSS JOIN your_table as t4 USING (id)
CROSS JOIN your_table as t5 USING (id)
WHERE t1.color = 'blue' and t2.color = 'purple' and t3.color= 'green' and t4.color= 'white' and t5.color= 'black'
! = 또는 NOT IN을 사용하려고하면 작동하지 않는 것 같습니다. 색상이 파란색, 보라색, 녹색, 흰색 (검정이 아닌)이되도록 쿼리를 작성하려면 어떻게해야합니까?
select e.id
from extra as e
where exists (select null from your_table as t where t.id = e.id and t.color = 'blue')
and exists (select null from your_table as t where t.id = e.id and t.color = 'purple')
and exists (select null from your_table as t where t.id = e.id and t.color = 'green')
and exists (select null from your_table as t where t.id = e.id and t.color = 'white')
and not exists (select null from your_table as t where t.id = e.id and t.color = 'black')
또는 이런 일이 아마 더 효율적인 것 :
select e.id
from extra as e
where 4 =
(select count(*)
from your_table as t
where t.id = e.id
and t.color in ('blue', 'purple', 'green', 'white'))
and 0 =
(select count(*)
from your_table as t
where t.id = e.id
and t.color in ('black'))
그래도 효과가 있지만 놀랍게도 실제로는 더 효율적입니다. 두 번째 쿼리보다 약 2-3 배 빠릅니다. 그러나 본래의 크로스 조인은 처음 것보다 약 2 배 빠릅니다. 이것은 존재하지 않는 무언가를 선택하는 비용입니까? – Roger
''your_table'에 ('id','color') 색인을 추가 할 수 있습니다. –
아, 문제가 될 것이라고 생각했습니다. ID가 인덱싱되었지만 두 번째 열은 인덱싱되지 않았습니다. 지금은 훨씬 빠릅니다. 두 쿼리 모두 거의 같은 속도 인 것처럼 보이지만 첫 번째 두 번째 쿼리에는 "종속 쿼리"가 적습니다. 따라서 더 나은 것으로 가정합니다. – Roger