MySQL: WHERE IN() 仅限于一行对等参数

MySQL: WHERE IN() limited to one row peer argument

我有一个 MySQL table 这样的:id | reference_id | name

我希望得到行 WHERE reference_id 是 IN 某个特定的值列表:SELECT * FROM TABLE WHERE reference_id IN(2,3);

问题是 table 将包含如下数据:

id | reference_id | name

1  | 1            | nameA
2  | 2            | nameB
3  | 2            | nameC
4  | 3            | nameD

通过 运行 查询,我将得到如下结果集:

id | reference_id | name

2  | 2            | nameB
3  | 2            | nameC
4  | 3            | nameD

有没有办法告诉 MySQL 只有 return 一个值对等 IN 参数?意思是,我想要一个结果集:

id | reference_id | name

3  | 2            | nameC
4  | 3            | nameD
select * from your_table
where id in
(
  select max(id)
  from your_table
  where reference_id in (2,3)
  group by reference_id
)

http://sqlfiddle.com/#!9/6412b/2

SELECT `table1`.* 
FROM `table1` 
LEFT JOIN `table1` t
ON `table1`.reference_id  = t.reference_id 
 AND `table1`.id<t.id
WHERE `table1`.reference_id IN(2,3)
  AND t.id IS NULL
GROUP BY `table1`.reference_id 

另一种方法是变量:

select  id,
        @reference_id:=reference_id as reference_id,
        name
from    table1 cross join (select @rn:=0,@reference_id:='') r
where   @rn:=case when @reference_id=reference_id
                  then @rn+1 else 1 end = 1
    and reference_id in (2,3)
order by reference_id

Fiddle: http://sqlfiddle.com/#!9/6412b/9/0