我有两个表user
和product
具有一对多关系(一个user
可能有多个product
)。
我想创建一个查询以获取所有同时具有橙和香蕉的user
。在下面的示例中,这将是john
和leeroy
。
如何制定查询条件?
只有一种情况,我会变成:
SELECT * FROM "user"
INNER JOIN "product" ON "product"."fk_user" = "user"."id"
WHERE "product"."product" = 'banana';
user
表
╔════╦═════════╗
║ id ║ name ║
╠════╬═════════╣
║ 1 ║ michael ║
╠════╬═════════╣
║ 2 ║ john ║
╠════╬═════════╣
║ 3 ║ leeroy ║
╠════╬═════════╣
║ 4 ║ tony ║
╚════╩═════════╝
product
表
╔═════════╦═════════╗
║ product ║ fk_user ║
╠═════════╬═════════╣
║ orange ║ 1 ║
╠═════════╬═════════╣
║ orange ║ 2 ║
╠═════════╬═════════╣
║ banana ║ 2 ║
╠═════════╬═════════╣
║ banana ║ 3 ║
╠═════════╬═════════╣
║ orange ║ 3 ║
╠═════════╬═════════╣
║ banana ║ 4 ║
╚═════════╩═════════╝
答案 0 :(得分:3)
您可以使用两个联接:
SELECT u.*
FROM user u
INNER JOIN product p1
ON p1.fk_user=u.id
AND p1.product='banana'
INNER JOIN product p2
ON p2.fk_user=u.id
AND p2.product='orange'
答案 1 :(得分:3)
按用户分组并使用 agateway:
cl_profile: "sl6.5-x86_64"
prefix: "aicgateway"
primary_role: "STANDARDV3"
requires_pool: false
ac-edge:
cl_profile: "sl6.5-x86_64"
prefix: "ac-edge"
primary_role: "STANDARDV3"
requires_pool: false
webnode:
cl_profile: "centos-5.6-x86_64-db-v2"
vlans: ["frontend"]
label: "Frontend"
prefix: "web"
primary_role: "FRONTEND"
requires_pool: false
检查用户的产品。
HAVING
编辑:我应该补充一点,有几种方法可以编写这种子查询。一个select *
from user
where id in
(
select fk_user
from product
group by fk_user
having count(case when product = 'orange' then 1 end) > 0
and count(case when product = 'banana' then 1 end) > 0
);
子句可以加快速度,使用这样的子句,您可以只计算发现的不同产品:
WHERE
答案 2 :(得分:3)
最直接的声明(IMHO)将使用两个IN
子句:
select *
from user
where id in
(
select fk_user
from product
WHERE product = 'orange')
and id in
(
select fk_user
from product
WHERE product = 'banana')
答案 3 :(得分:1)
If you just want the user id and not the name, you can use aggregation:
SELECT p.fk_user
FROM product p
WHERE p.product in ('banana', 'orange')
GROUP BY p.fk_user
HAVING COUNT(*) FILTER (WHERE p.product = 'banana') > 0 AND
COUNT(*) FILTER (WHERE p.product = 'orange') > 0;
If you need additional columns from user
as well, I would go with the IN
version suggested by DStanley, although I would use EXISTS
rather than IN
.
答案 4 :(得分:0)
这是relational-division的情况。
如果(就像典型情况一样,您的示例数据似乎也支持)...
FOREIGN KEY
约束,用于强制引用完整性UNIQUE
的{{1}}约束-(对于我的查询,隐含providing the perfect index)..然后它就快了:
product(product, fk_user)
我们在这里收集了大量基础技术:
最佳选择取决于缺少的规格-以及个人偏好。
此外:user
是一个保留字,请勿将其用作表名。