6

我有一个 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_id,我运行查询,

SELECT car_id, part_id FROM T1 WHERE car_id=1

并得到结果:

car_id   part_id
  1        1  
  1        2  
  1        8    

现在,我想找到所有剩余的至少包含(例如 >= 2/3)与 car_id=1 关联的 part_id 的 car_id。(在这个例子中,我应该得到所有 car_ids 至少有 2 个 part_ids 1,2 和 8,如我的 SELECT 查询之后所示。所以,我应该得到 car_ids 1,10 和 20)。

我可以使用以下方法找到包含所有 part_ids 1、2 和 8 的 car_ids:

SELECT 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_id:

SELECT 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 之间指定某个数字?

4

3 回答 3

1

To get all car_ids that have 2 or more of car 1's part_ids do

SELECT car_id, 
       group_concat(part_id) as part_ids
FROM T1
WHERE part_id in (SELECT part_id FROM T1 WHERE car_id = 1)
group by car_id
having count(distinct part_id) >= 2
于 2012-12-26T17:25:23.567 回答
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

于 2012-12-26T18:13:45.603 回答
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(),尽管您没有在问题中指定这一点。

于 2012-12-26T18:04:26.260 回答