我在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 语句来实现这一目标?
谢谢。
最佳答案
您可以通过使用查询生成派生表来完成此操作。然后将此派生表与原始表连接起来:
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的预期结果集。如果您希望所有行都具有与前 3 个评分值相关的 (Category, Type)
值,那么您可以使用:
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
关于jquery - 如何在多列中选择特定且不同数量的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32782622/