jquery - 如何在多列中选择特定且不同数量的记录?

标签 jquery mysql

我在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

Demo here

关于jquery - 如何在多列中选择特定且不同数量的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32782622/

相关文章:

javascript - Express.js - 尝试从 mysql 提取数据时出错

php - 当运行 `SELECT INNER JOIN WHERE t1.column=t2.column` 并且有多个匹配时,如何控制选择哪个匹配?

php - 仅使用 Sphinx 搜索引擎 (API-PHP) 进行通配符匹配和邻近度精确匹配

php - SQL 语法错误但使用正确的 sql 查询

javascript - 如何每隔一个项目添加一个带有类的div

javascript - jQuery .ajax() JSONP 响应的间歇性类型错误

jquery - 打印页面内容覆盖页眉

javascript - 脚本中的 jQuery attr 和 prop 组合

javascript - 获取图像变量 src 属性

mysql - 在整个MySQL数据库中搜索日期 "0000-00-00 00:00:00"?