我有两张桌子:[TEXT],[CATEGORY] 每个文本项都有一个类别 以下sql语句检索具有“art”类别
的文本项SELECT * from [TEXT], [CATEGORY] WHERE [CATEGORY].[id]=[TEXT].[CATEGORY_id] AND
[CATEGORY].[name] IN ("Art") LIMIT 10
我想要做的是从每个类别中检索10个文本项目。
10来自艺术,10来自哲学,10来自科学......
答案 0 :(得分:3)
假设你确实意味着MySQL,最快的解决方案涉及变量:
select t.*
from (SELECT *,
@rn := if(@cname = c.name, @rn + 1, 1) as rn
@cname := c.name
from `TEXT` t join
CATEGORY c
on c.id = t.CATEGORY_id cross join
(select @cname := '', @rn := 0) const
order by c.name
) t
where rn <= 10;
我特别不喜欢这个解决方案,因为MySQL不保证在@rn
的分配之前发生@cname
的分配。但是,它确实在实践中发挥作用。
编辑:
以上在MySQL中有效。在SQLite中,您需要使用查询进行计数:
select t.*
from (SELECT *,
(select count(*) from Text t2 where t2.Category_id = t.Category_Id and t2.id <= t.id
) as seqnum
from TEXT t join
CATEGORY c
on c.id = t.CATEGORY_id
) t
where seqnum <= 10;
这实际上是标准的SQL,但通常性能不太好,所以其他选择是首选。
注意:这假设Text
中有一些列标识每一行。我称之为id
。
答案 1 :(得分:0)
试试这个:
SELECT
CATEGORY.NAME,
@curRank := @curRank + 1 AS rank,
TEXT.NAME
FROM TEXT
JOIN ( select NAME.ID, @curRank := 0 from CATEGORY) CATEGORY
ON CATEGORY.ID = TEXT.ID
) CATEGORY
ON CATEGORY.ID = TEXT.ID
WHERE rank <= 10
ORDER BY
CATEGORY.NAME,
rank
答案 2 :(得分:0)
SELECT * FROM [CATEGORY]
JOIN (SELECT [TEXT].[CATEGORY_id],
IF( @previous = [TEXT].[CATEGORY_id],
@temp := @temp + 1, @temp := 1) cnt,
@previous := [TEXT].[CATEGORY_id]
FROM [TEXT] ORDER BY [TEXT].[CATEGORY_id] ) t
WHERE [CATEGORY].[id]= t.[CATEGORY_id] AND
[CATEGORY].[NAME] IN ("Art") and cnt <= 10