MYSQL 过滤器将行乘以两个 id 列表
MYSQL filter multiply row by two lists of id
我有结果:
item_id subitem_id
----------------------
1 35
1 25
1 8
2 10
2 25
3 60
4 35
4 25
4 44
5 1
5 23
5 15
5 13
5 9
我有两个子项目列表
(25,44,1)
(8,9)
如何设置 where 子句以过滤结果 return this
item_id subitem_id
----------------------
1 35
1 25 <-- first set
1 8 <-- second set
-----------------
5 1 <-- first set
5 23
5 15
5 13
5 9 <-- second set
因为这个 item_id
包含来自两个列表的 subitem_id
SELECT
`item_id`
FROM table
WHERE `subitem_id` in (25,44,1)
AND `subitem_id` in (8,9)
没用,因为一次 subitem_id
有一个 id(不是所有列表)
P.S。
这是一个简单的例子,实际上我们有超过 100k 的记录和一些连接结构
我认为您正在尝试确保 item_ID 具有 2 个不同集合中的子类别..
Select * from table A
where exists (Select 1 from table B where A.Item_Id = B.Item_ID and subitem_ID in (25,44,1))
and exists (Select 1 from table C where A.Item_Id = C.Item_ID and subitem_ID in (8,9))
http://sqlfiddle.com/#!9/71c28e5/3
SELECT t1.*
FROM (
SELECT DISTINCT(t1.item_id)
FROM t1
INNER JOIN t1 t2
ON t1.item_id = t2.item_id
AND t2.subitem_id in (8,9)
WHERE t1.subitem_id in (25,44,1)
) t
LEFT JOIN t1
ON t.item_id = t1.item_id
避免mysql执行大量记录的另一种方法:
http://sqlfiddle.com/#!9/71c28e5/10
SELECT t1.*
FROM t1
WHERE item_id in (
SELECT DISTINCT(t1.item_id)
FROM t1
INNER JOIN t1 t2
ON t1.item_id = t2.item_id
AND t2.subitem_id in (25,44,1)
WHERE t1.subitem_id in (8,9)
)
我有结果:
item_id subitem_id
----------------------
1 35
1 25
1 8
2 10
2 25
3 60
4 35
4 25
4 44
5 1
5 23
5 15
5 13
5 9
我有两个子项目列表
(25,44,1)
(8,9)
如何设置 where 子句以过滤结果 return this
item_id subitem_id
----------------------
1 35
1 25 <-- first set
1 8 <-- second set
-----------------
5 1 <-- first set
5 23
5 15
5 13
5 9 <-- second set
因为这个 item_id
包含来自两个列表的 subitem_id
SELECT
`item_id`
FROM table
WHERE `subitem_id` in (25,44,1)
AND `subitem_id` in (8,9)
没用,因为一次 subitem_id
有一个 id(不是所有列表)
P.S。 这是一个简单的例子,实际上我们有超过 100k 的记录和一些连接结构
我认为您正在尝试确保 item_ID 具有 2 个不同集合中的子类别..
Select * from table A
where exists (Select 1 from table B where A.Item_Id = B.Item_ID and subitem_ID in (25,44,1))
and exists (Select 1 from table C where A.Item_Id = C.Item_ID and subitem_ID in (8,9))
http://sqlfiddle.com/#!9/71c28e5/3
SELECT t1.*
FROM (
SELECT DISTINCT(t1.item_id)
FROM t1
INNER JOIN t1 t2
ON t1.item_id = t2.item_id
AND t2.subitem_id in (8,9)
WHERE t1.subitem_id in (25,44,1)
) t
LEFT JOIN t1
ON t.item_id = t1.item_id
避免mysql执行大量记录的另一种方法:
http://sqlfiddle.com/#!9/71c28e5/10
SELECT t1.*
FROM t1
WHERE item_id in (
SELECT DISTINCT(t1.item_id)
FROM t1
INNER JOIN t1 t2
ON t1.item_id = t2.item_id
AND t2.subitem_id in (25,44,1)
WHERE t1.subitem_id in (8,9)
)