从不同的列表中选择

时间:2011-08-30 13:06:51

标签: mysql

我正在运行以下查询:

SELECT DISTINCT hardware_id, model, make from Table1 order by hardware_id;

我的问题是,在结果集中,我希望看到的结果只有在hardware_id出现多次时才会出现。

示例:

硬件1 model1 make 1

硬件1 model2 make 1

hardware 2 model2 make 1> 我不想看到这个,因为只有1次出现硬件2

硬件3 model2 make 1

硬件3 model2 make 1

知道我该怎么做吗?

=====

问题是由于我的DISTINCT标志,我无法使用以下查询:

SELECT hardware_id,model,make from Table1 WHERE hardware_id IN (SELECT DISTINCT hardware_id, model, make from Table1 order by hardware_id) where count(hardware_id) >= 2;

我绝对需要使用distinct(hardware_id,model,make)

有什么想法吗?

4 个答案:

答案 0 :(得分:3)

SELECT hardware_id, model, make 
FROM Table1 AS t
WHERE EXISTS
      ( SELECT * 
        FROM Table1 AS td
        WHERE td.hardware_id = t.hardware_id
          AND td.id <> t.id                 --- if id is the PK of the table
      )
ORDER BY hardware_id

由于该表具有重复的(hardware_id, model, make)三元组,您可以改为使用它:

SELECT DISTINCT hardware_id, model, make 
FROM Table1 AS t
WHERE EXISTS
      ( SELECT * 
        FROM Table1 AS td
        WHERE td.hardware_id = t.hardware_id
          AND (td.model, td.make) 
              <> (t.model, t.make)               
      )
ORDER BY hardware_id

答案 1 :(得分:2)

SELECT hardware_id, model, make 
FROM table1
GROUP BY hardware_id  --  group by orders the rows ASC as a side effect.
HAVING count(hardware_id) > 1

但是,这会为modelmake选择* random *值 您可能需要考虑使用:

SELECT hardware_id, GROUP_CONCAT(DISTINCT CONCAT(model,' - ',make)) AS modelmakes 
FROM table1
GROUP BY hardware_id  --  group by orders the rows ASC as a side effect.
HAVING count(hardware_id) > 1

您也可以针对第一个选择进行连接以获取所需的所有行,您不需要明确。

SELECT t1.hardware_id, t1.make, t1.make 
FROM table1 t1
INNER JOIN (
    SELECT hardware_id 
    FROM table1
    GROUP BY hardware_id  
    HAVING count(hardware_id) > 1
           ) t2 ON (t1.hardware_id = t2.hardware_id)

答案 2 :(得分:1)

您需要子查询重复的硬件ID,并将此列表加入您的查询。子查询可以是:

SELECT hardware_id
FROM Table1
GROUP BY hardware_id
HAVING COUNT(hardware_id) > 1

然后,您可以将其加入原始查询:

SELECT hardware_id, model, make 
FROM Table1
INNER JOIN (
    SELECT t1.hardware_id
    FROM Table1 t1
    GROUP BY t1.hardware_id
    HAVING COUNT(t1.hardware_id) > 1
) AS join1 ON (join1.hardware_id = Table1.hardware_id)
ORDER BY hardware_id ASC;

答案 3 :(得分:0)

尝试此查询:

SELECT hardware_id, model, make from Table1 where hardware_id in 
    (select hardware_id 
     from TABLE1 group by hardware_id having count(hardware_id) > 1);

另一个版本:

SELECT hardware_id, model, make from Table1 t where EXISTS( 
    select hardware_id 
     from TABLE1 where hardware_id = t.hardware_id 
     group by hardware_id having count(hardware_id) > 1
);