其他列条件

时间:2015-05-19 09:47:32

标签: mysql sql

表1:

我需要所有item_id记录,其中image_id = 1且item_id多次出现在表格中:

因此,对于下表(让我们称之为my_table):

item_id     image_id
-------     --------
   1           1
   1           5
   1           6
   2           1
   3           1
   4           1
   6           1
   6           33
   6           34

item_id记录的输出应为:1,6

我试过了:

    SELECT m_t1.item_id
    FROM my_table m_t1
    INNER JOIN
    (SELECT COUNT(item_id)
    FROM my_table
    GROUP BY item_id
    HAVING COUNT(item_id)>1) m_t2
    ON m_t2.image_id=1
    WHERE m_t1.item_id=m_t2.item_id

3 个答案:

答案 0 :(得分:2)

一种方法是使用exists

select 
 t1.item_id 
 from my_table t1 
 where t1.image_id = 1 
 and exists( 
   select 1 from my_table t2 
   where t2.item_id = t1.item_id 
   and t2.image_id <> 1 
);

答案 1 :(得分:2)

SELECT item_id FROM my_table 
WHERE image_id = 1 
  AND item_id IN (SELECT item_id FROM my_table GROUP BY item_id HAVING COUNT(*) > 1);

答案 2 :(得分:0)

   select * from item where item_id in (
   select item_id  from item 
   group by item_id
   having count (item_id ) > 1) 
   and image_id = 1