简体   繁体   English

SQL查询返回的列的值大于某个最小值(取决于类别)的行?

[英]SQL query to return rows with the value of a column above a certain minimum value depending on category?

If I have for example these 2 tables: 例如,如果我有这两个表:

table1: 表格1:

item       category     rating
------     --------     ------
table      furniture      6
chair      furniture      5
sofa       furniture      7
bed        furniture      4
apple      food           7
banana     food           6
spinach    food           9
almonds    food           8
happiness  feeling        7
compassion feeling        6
love       feeling        8
admiration feeling        7

and table2: 和表2:

category     minimum_rating
--------     --------------
furniture          6 
food               8
feeling            7

and taking into consideration that the value minimum_rating for each category would be revised each month, so it would change... How would I query table1 in relation to table2 so that it would take the value of minimum_rating for that category of the item and return only those items in table1 with a rating equal or above the minimum rating? 并考虑到每个类别的minimum_rating值每个月都会修改,因此它会发生变化...我将如何相对于table2查询table1,以便它将该项的该类别的minimum_rating值取回仅表1中那些评级等于或高于最小评级的项目? In this case the query would be expected to return: 在这种情况下,查询将返回:

item       category     rating
------     --------     ------
table      furniture      6
sofa       furniture      7
spinach    food           9
almonds    food           8
happiness  feeling        7
love       feeling        8
admiration feeling        7

Thanks a lot for your knowleadgeable input! 非常感谢您的宝贵意见!

I think you need a JOIN on both the table like below. 我认为您需要在两个表上都JOIN ,如下所示。 You can probably as well say t1.rating = t2.minimum_rating 您可能还可以说t1.rating = t2.minimum_rating

select t1.*
from table1 t1 join table2 t2 on t1.category = t2.category
where t1.rating >= t2.minimum_rating;

A simple join should do the job: 一个简单的联接就可以完成这项工作:

Select a.* from table1 as a
 inner join table2 as b on a.furniture = b.furniture and a.rating >=     b.minimum_rating;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM