仅从 mariadb 中获取完全匹配的行 table
Fetching Exact matching rows only From mariadb table
我有一个 table 如下所示
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);
当我们select查询
1。
Select 不同 contract_id
来自 tmp_test
其中 FIND_IN_SET(item_id, '1,2');
输出需要
12, 18
-
Select Distinct contract_id
From tmp_test
Where FIND_IN_SET(item_id, '1');
输出需要
14
-
Select Distinct contract_id
From tmp_test
Where FIND_IN_SET(item_id, '1,2,3');
输出需要
10, 20
-
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';
我有一个 table 如下所示
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);
当我们select查询
1。 Select 不同 contract_id 来自 tmp_test 其中 FIND_IN_SET(item_id, '1,2');
输出需要
12, 18
-
Select Distinct contract_id From tmp_test Where FIND_IN_SET(item_id, '1');
输出需要
14
-
Select Distinct contract_id From tmp_test Where FIND_IN_SET(item_id, '1,2,3');
输出需要
10, 20
-
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';