我想检查一个元组是否在选定的行中。
我有用户,例如下一个(简化):
user_id int,
company_id,
subcompany_id
和 org_cat 模型,例如下一个:
cat_id,
company_id,
subcompany_id
我想为cat_id = 2的所有类别的用户选择用户ID。
接下来是错的:
SELECT
user_id
FROM "user"
WHERE
company_id IN ( SELECT company_id FROM org_cat where cat_id=2 )
AND
subcompany_id IN ( SELECT subcompany_id FROM org_cat where cat_id=2 );
因为如果我们有组合{1,3},{2,3},{3,3}(在公司中为company_id,subcompany_id和company_id = 1,subcompany_id = 3在org_cat中,cat_id = 2 则所有行都将从用户中选择 - 这是不正确的。
我的意思是下一个解释错误的查询:
SELECT
user_id
FROM "user"
WHERE
( company_id, subcompany_id ) IN ( SELECT company_id, subcompany_id FROM org_cat where cat_id=2 );
因为postgresql可能不认为(company_id,subcompany_id)是元组。
请帮忙构建一个正确的查询吗?
更新
实际上,带有“(company_id,subcompany_id)IN ...”的变体也有效但比答案慢一点。谢谢, a_horse_with_no_name !
答案 0 :(得分:3)
SELECT user_id
FROM "user" U join org_cat on U.company_id = org_cat.company_id
AND U.subcompany_id = org_cat.subcompany_id
WHERE org_cat.cat_id = 2
SQL小提琴:click here
答案 1 :(得分:0)
为什么不直接连接元组中的值:
WHERE CAST(company_Id as VARCHAR) + '|' + CAST(subcompany_id as VARCHAR) IN
(SELECT CAST(company_Id as VARCHAR) + '|' + CAST(subcompany_id as VARCHAR) FROM ... )