我有一个mysql表T1,它由两列INT组成,它们将car_id链接到part_id。单个car_id可以具有多个part_id,并且相同的part_id可以对应于多个car_id。例如,
car_id part_id
1 1
1 2
1 8
2 3
3 4
4 2
4 6
...
10 1
10 2
...
20 1
20 2
20 8
要获取与car_id = 1关联的所有part_ids,我运行查询
SELECT car_id, part_id FROM T1 WHERE car_id=1
并得到结果:
car_id part_id
1 1
1 2
1 8
现在,我想找到至少包含与car_id = 1相关联的part_ids(例如> = 2/3)的所有剩余car_id。 (在这个例子中,我应该得到所有car_ids至少有2个part_id 1,2和8,如我的SELECT查询后所示。所以,我应该得到car_ids 1,10和20)。
我可以使用:
找到包含所有part_ids 1,2和8的car_idsSELECT car_id, part_id
FROM T1
WHERE part_id = ALL (SELECT part_id FROM T1 WHERE car_id=1). The result is car_ids 1 and 20.
我可以使用:
找到包含任何值1,2和8的car_idsSELECT car_id, part_id
FROM T1
WHERE part_id = ANY (SELECT part_id FROM T1 WHERE car_id=1). The result is car_ids 1,4,10 and 20.
如何在ANY和ALL之间指定一些数字?
答案 0 :(得分:1)
要获得包含2个或更多汽车car_id
的{{1}}的所有1
个
part_id
答案 1 :(得分:0)
这是一种方式:
select car_id
from (select cp.car_id,
sum(case when cp.part_id is not null and cp1.part_id is not null then 1 else 0 end) as PartsInCommon,
sum(case when cp.part_id is not null and cp1.part_id is null then 1 else 0 end) as ThisCarOnly,
sum(case when cp.part_id is null and cp1.part_id is not null then 1 else 0 end) as ThatCarOnly
from CarParts cp full outer join
(select part_id
from CarParts cp
where car_id = 1
) cp1
on cp.part_id = cp1.part_id
group by cp.car_id
) t
where PartsInCommon / (PartsInCommon + ThisCarOnly + ThatCarOnly) >= 2.0/3
此查询计算两辆车或两辆车共用的零件数量。然后where
子句定义特定条件。
如果你想要部分列表,那么Juergen对group_concat()
有正确的想法,尽管你没有在问题中指明这一点。
答案 2 :(得分:0)
尝试此查询。我尽可能多地尝试
SELECT
car_id,
GROUP_CONCAT(part_id)
FROM cars
WHERE FIND_IN_SET
(part_id ,(SELECT GROUP_CONCAT(part_id) FROM cars WHERE car_id = 1))
GROUP BY car_id
HAVING COUNT(part_id) >= 2
这是sqlfiddle演示http://sqlfiddle.com/#!2/8e563/17