我的桌子看起来像这样
id | string | foreign_id
---------------------------
1 | house | 5
2 | garden | 6
3 | window | 5
...
我有一个字符串数组,我想获取所有匹配的所有外国 id元素匹配的所有外部 id。所以我有一个像这样的数组 [house, window] 然后我想得到 5。字符串数组最多可以有 10 个元素。
合适的sql语句长什么样子?
尝试类似:
select foreign_id
from your_table
where string in ('house', 'window')
group by foreign_id
having count(distinct string) = 2;
- 假设生成查询的任何东西都可以计算请求的不同字符串的数量。
(编辑以下评论)
假设您希望foreign_id
同时匹配“house”和“window”,请使用:
SELECT t.foreign_id
FROM YOUR_TABLE t
WHERE t.string IN ('house', 'window')
GROUP BY t.foreign_id
HAVING COUNT(DISTINCT t.string) = 2
HAVING 计数必须等于 IN 子句中定义的数值。
字符串数组最多可以有 10 个元素。
这将需要使用动态 SQL。我会提供一个例子,但你没有提到你正在使用什么数据库......
动态生成查询,为每个数组元素添加一次注释行:
Select distinct foreign_id
from myTable
where 1=1
--add the following line once for each array element
and foreign_id in (select foreign_id from myTable where string = 'value')
所以给出你的例子,查询将是
Select distinct foreign_id
from myTable
where 1=1
and foreign_id in (select foreign_id from myTable where string = 'house')
and foreign_id in (select foreign_id from myTable where string = 'window')
这应该返回您正在寻找的内容。
任何问题?
// 1=1 只是为了让动态部分每次都相同。我会排除 1=1 并让第一个条目跳过“和”
@Mark Bannister 很接近,但是当字符串和foreign_id 重复时,他会失败。这行得通,但是自从我对 SQL 做任何有用的事情以来已经有好几年了,所以可能有更好的方法。
SELECT foreign_id FROM (
SELECT distinct string, foreign_id FROM your_table
WHERE string in ('house', 'window')) as T
GROUP BY T.foreign_id HAVING count(foreign_id) = 2;
像 Mark 一样,我假设您可以动态填充 in 子句以及 having 子句的 RHS。存储过程在这里可能会有所帮助。
select string, foreign_id
from table
group by foreign_id