我在MySql数据库中有这样的表。
"table1" ____________________________________________________ id Category Type rating Value ---------------------------------------------------- 1 1 1 5 23 2 1 1 6 27 3 2 1 4 26 4 2 2 2 25 5 3 1 4 21 6 3 1 5 28
我想在此表中选择具有唯一类别和类型的特定数量的不同文档。像这样:
select distinct category, type from table1 order by rating desc limit 0,3
"table2" __________________________ id Category Type -------------------------- 1 1 1 5 3 1 3 2 1
然后从表中选择具有此类别和类型的所有值。
select id,value from table1 where type and category is in table2
"table3" ____________________________________________________ id Category Type rating Value ---------------------------------------------------- 1 1 1 5 23 2 1 1 6 27 5 3 1 4 21 6 3 1 5 28 3 2 1 4 26
我如何使用一个Sql语句来实现这个目标?
THX。
答案 0 :(得分:2)
您可以使用查询生成派生表来执行此操作。然后将此派生表与原始表连接:
SELECT id, t1.Category, t1.Type, rating, Value
FROM table1 AS t1
INNER JOIN (SELECT DISTINCT category, type
FROM table1
ORDER BY rating DESC limit 0,2) AS t2
ON t1.category = t2.category AND t1.type = t2.type
但是上面并没有实际返回OP的预期结果集。如果您希望所有行的(Category, Type)
值与前3个评级值相关,那么您可以使用:
SELECT id, t1.Category, t1.Type, rating, Value
FROM table1 AS t1
INNER JOIN (
SELECT category, type
FROM table1
GROUP BY category, type
ORDER BY MAX(rating) DESC LIMIT 0,3
) AS t2 ON t1.category = t2.category AND t1.type = t2.type