我有一个表“文章”,其中有一个列“公司”,其中包含公司列表或文章类型 - 我知道这很糟糕,但这不是我的数据库。 :)假设每种类型都有 n 条款。我需要选择第一篇文章(基于年份或任何其他标准)。像这样:
select * from details where (company = 'aaa' or company = 'bbb' or ...)
我知道这些类型是什么,所以它们可以被硬编码。我只需限制每种类型的第一篇文章。谢谢!
修改
给出样本数据:
id company copy issue ------------------------ 1 apple 'abc' NULL 2 bmw 'abc' NULL 3 ibm 'abc' NULL 4 news 'abc' 2 5 news 'abc' 3 6 seagate 'abc' NULL 7 events 'abc' 1 8 features 'abc' 5 9 samsung 'abc' NULL
我需要第4,7,8行。
EDIT2
很抱歉,如果我不清楚的话。本质上,该表包含两种不同类型的数据。一个是公司信息,一个是文章信息。基本上我需要这样做:
select * from articles where company = "news" order by issue limit 1;
select * from articles where company = "events" order by issue limit 1;
select * from articles where company = "features" order by issue limit 1;
但只有一个查询。
答案 0 :(得分:3)
这样的事可能
select * from details d
where company in ('news', 'events', 'features')
and not exists (
select 1 from details d_
where d_.company = d.company
and d_.id < d.id -- provide your sortable criteria here
)
答案 1 :(得分:3)
此查询:
select t1.* from t t1
left join t t2
on t1.company = t2.company and t1.id > t2.id
where t2.id is null and t1.company in ('news', 'events', 'features')
将返回:
+----+----------+------+ | ID | COMPANY | COPY | +----+----------+------+ | 4 | news | abc | | 7 | events | abc | | 8 | features | abc | +----+----------+------+
这就是你要找的东西吗?
注意:当您说the first article
时,我认为订单是由ID
字段提供的
你可以玩它here
修改强>
修改后,查询几乎相同,只需将排序字段更改为issue
而不是id
:
select t1.* from t t1
left join t t2
on t1.company = t2.company and t1.issue > t2.issue
where t2.id is null and t1.company in ('news', 'events', 'features')
答案 2 :(得分:0)
假设“company”和“publication_date”是表“details”中的列,那么类似于:
select *
from details
where company in ('aaa', 'bbb', ...)
and publication_date between '2012-02-01' and '2012-03-01'
order by publication_date desc
limit 1
答案 3 :(得分:0)
您正在尝试group by
接下来,您需要order by
问题列
那你只需要第一行。
我使用group concat创建一个列表,
然后提取有序列表group_concat(copy order by copy)
中的第一个字符串。
select
id,
company,
substring(
group_concat(copy order by copy),
1,
case when substring_index(group_concat(copy order by copy),',',1) > 1
then substring_index(group_concat(copy order by copy),',',1)-1
else 1 end
) as copy
from details d
where company in ('news', 'events', 'features')
group by company
*列表group_concat(copy order by copy)
不能太长,这取决于您的数据。