存在于多个选择中的 SQL 选择列.选择与列表中所有值匹配的值

  • 本文关键字:选择 于多个 SQL 存在 列表 sql sqlite
  • 更新时间 :
  • 英文 :


此选择语句:

select * from favoritetags where tagid = 4

返回

ID |tagid | favoriteid |
12 |4     |12          |
50 |4     |42          |
42 |4     |34          |

同样,声明:

select * from favoritetags where tagid = 29

返回:

ID |tagid | favoriteid |
49 |29    |41          |
51 |29    |34          |

我只想得到两者中的收藏夹列表。

然后我想概括一下,我只能获得那些与 tagid 列表共同具有 faviriteid 的行。 其中 tagid 在(29,4,6)或任何数量的值中。

以下查询提供表中多次出现的所有标记。

SELECT * FROM #tags T JOIN 
(
SELECT tagid,COUNT(*) AS [Count] FROM #tags
GROUP BY tagid
HAVING COUNT(*)>1
)G
ON t.tagid=g.tagid
ORDER BY t.tagid 

您可以使用聚合:

select favoriteid
from favoritetags
where tag_id in (4, 29)
group by favoriteid
having count(distinct tag_id) = 2

where子句筛选属于愿望清单tag_id。查询按favoriteid聚合,并确保每个favoriteid有两个不同的tag_id(这实际上意味着429都可用(。

这可以很容易地扩展到更多tag_id

select favoriteid
from favoritetags
where tag_id in (4, 29, 6)
group by favoriteid
having count(distinct tag_id) = 3

如果列表以逗号分隔的字符串表示,例如:'4,29'然后在以下语句中使用它:

select favoriteid
from favoritetags
where ',' || '4,29' || ',' like '%,' || tag_id || ',%' 
group by favoriteid
having count(distinct tag_id) = length('4,29') - length(replace('4,29', ',', '')) + 1

所以声明是:

select favoriteid
from favoritetags
where ',' || ? || ',' like '%,' || tag_id || ',%' 
group by favoriteid
having count(distinct tag_id) = length(?) - length(replace(?, ',', '')) + 1

然后用您的列表替换?
请参阅演示。

或者,您可以通过交叉加入列表来仅进行 1 次替换:

select f.favoriteid
from favoritetags f cross join (select ? list) t
where ',' || t.list|| ',' like '%,' || f.tag_id || ',%' 
group by f.favoriteid
having count(distinct f.tag_id) = length(t.list) - length(replace(t.list, ',', '')) + 1

请参阅演示。

如果您希望在 select 语句中查询值,请使用带有VALUESCTE

with list(tag) as (values (4), (29))
select favoriteid
from favoritetags
where tag_id in (select tag from list) 
group by favoriteid
having count(distinct tag_id) = (select count(*) from list) 

请参阅演示。

最新更新