0

考虑下表

CREATE TABLE `temp` (
  `id` int(11) NOT NULL,
  `lang` char(2) COLLATE utf8_unicode_ci NOT NULL,
  `channel` char(2) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`,`lang`,`channel`)
)

insert into `temp` (`id`, `lang`, `channel`, `name`) values('1','fr','ds','Jacket');
insert into `temp` (`id`, `lang`, `channel`, `name`) values('1','en','ds','Jacket');
insert into `temp` (`id`, `lang`, `channel`, `name`) values('2','en','ds','Jeans');
insert into `temp` (`id`, `lang`, `channel`, `name`) values('3','en','ds','Sweater');
insert into `temp` (`id`, `lang`, `channel`, `name`) values('1','de','ds','Jacket');

问题是我如何才能找到哪些带有 lang en 的条目对于 fr 不存在?我的头被卡住了,我相信这是一个微不足道的问题,但我现在有一个问题。

4

3 回答 3

1

有几种方法可以实现这一点。一种方法是使用子选择 withnot exists子句:

select id, channel
from temp t1
where t1.lang = 'en'
and not exists (
  select 1
  from temp t2
  where t2.lang = 'fr'
  and t1.id = t2.id
)

或者,您可以使用外部联接:

select t1.id, t1.channel
from temp t1
left outer join temp t2 on t1.id = t2.id
where t1.lang = 'en'
and t2.id is null
于 2013-08-28T13:40:38.353 回答
1

基于@AleksG

SELECT t1.id, t1.channel, t1.name
FROM temp t1
LEFT JOIN temp t2 ON t1.id = t2.id AND t2.lang = 'fr'
WHERE t1.lang = 'en' AND t2.lang IS NULL 
于 2013-08-28T13:43:44.087 回答
1

您可以通过聚合来做到这一点:

select t.channel, t.name
from temp t
group by t.channel, t.name
having sum(case when t.lang = 'fr' then 1 else 0 end) = 0 and
       sum(case when t.lang = 'en' then 1 else 0 end) > 0;

子句中的第一个条件having计算法语出现的次数。第二个计算英语出现的次数。如果法语没有,而英语至少有一个,则频道和名称在结果集中。

于 2013-08-28T13:43:52.830 回答