programing

mariadb 테이블에서 정확하게 일치하는 행만 가져오는 중

javajsp 2023. 9. 1. 20:34

mariadb 테이블에서 정확하게 일치하는 행만 가져오는 중

아래와 같은 테이블이 있습니다.

Create Table tmp_test (
    id int(11) unsigned Auto_increment primary key , 
    contract_id int(11) unsigned, 
    item_id int(11) unsigned
);

Insert Into tmp_test (contract_id,item_id)
Values (10,1),(10,2),(10,3),(12,1),(12,2),(14,1),
(16,1),(16,2),(16,3),(16,4),(18,1),(18,2),(20,1),
(20,2),(20,3),(22,2),(22,3),(22,4),(24,1),(24,4);

쿼리를 선택할 때

고유 contract_id From tmp_test Where FIND_를 선택합니다.IN_SET(item_id, '1,2');

출력 요구 사항

12, 18
  1.   Select Distinct contract_id 
      From tmp_test 
      Where FIND_IN_SET(item_id, '1'); 
    

출력 요구 사항

14
  1.   Select Distinct contract_id 
      From tmp_test 
      Where FIND_IN_SET(item_id, '1,2,3'); 
    

출력 요구 사항

10, 20
  1.   Select Distinct contract_id 
      From tmp_test 
      Where FIND_IN_SET(item_id, '4,1'); 
    

출력 요구 사항

24

한 번의 쿼리로 이를 달성할 수 있도록 도와주십시오.

안부 전해요,

파이살

너는 원한다contract_id입력 목록의 모든 값을 포함하고 다른 값은 포함하지 않습니다.

집계와 다음을 사용하여 이 구문을 지정할 수 있습니다.having절:

select contract_id
from tmp_test
group by item_id
having sum(item_id in (1, 2)) = 2 and sum(item_id not in (1, 2)) = 0

아니면 당신이 원한다면요find_in_set():

having sum(find_in_set(item_id, '1,2')) = 2 and sum(find_in_set(item_id, '1,2') = 0) = 0
Select contract_id From (
Select contract_id,group_concat(item_id order By item_id) items From tmp_test 
Group By contract_id  ) sb
Where items Like '1,2';

언급URL : https://stackoverflow.com/questions/63850413/fetching-exact-matching-rows-only-from-mariadb-table