简体   繁体   English

您可以简化此查询吗?

[英]Could you simplify this query?

I have a table with this structure: 我有一个具有这种结构的表:

CREATE  TABLE IF NOT EXISTS `mydb`.`sizes` (
  `id_size` INT NOT NULL ,
  `cm_min` INT NOT NULL ,
  `cm_max` INT NOT NULL ,
  PRIMARY KEY (`id_size`) )
ENGINE = InnoDB;

This query returns the width and the height of the size 5: 此查询返回大小5的宽度和高度:

select cm_min, cm_max from sizes where id_size = 5;

which are: 哪个是:

45, 56

Well, I want to get all the sizes that have the cm_min or cm_max between this range. 好吧,我想获得所有cm_min或cm_max在此范围之间的大小。 I tought something like this: 我坚强的像这样:

http://sqlfiddle.com/#!2/83e93/51 http://sqlfiddle.com/#!2/83e93/51

It works, but there is sizes that are not between any range. 可以,但是大小不在任何范围内。 I mean, if i have this: 我的意思是,如果我有这个:

id_size    cm_min    cm_max
1          56        59
2          63        67
3          70        74
4          76        79
5          83        86
6          60        62
7          12        14

If I've the values of the id_size 6, and I execute the previous query it'll returns 0 rows selected, and I want get the id_size of the sizes higher and smaller than this, although not strictly between the values. 如果我具有id_size 6的值,并且执行上一个查询,它将返回选择的0行,我希望获得大于或小于此值的id_size,尽管并非严格地介于两个值之间。 In this case would return: 在这种情况下将返回:

id_size    cm_min    cm_max
1          56        59
2          63        67

Or for example if have the values of te id_size 7 which is the minor value, i need get the next minor value, in my case is: 或者例如,如果具有te id_size 7的值为次要值,我需要获取下一个次要值,在我的情况下是:

id_size    cm_min    cm_max
1          56        59

Or if i've the higher values I'd need the id of the size wich has the second higher values. 或者,如果我具有较高的值,则需要具有第二个较高值的大小的id。

Then if the first query that i posted doesn't has any result I do this: http://sqlfiddle.com/#!2/83e93/32/0 然后,如果我发布的第一个查询没有任何结果,我可以这样做: http : //sqlfiddle.com/#!2/83e93/32/0

It works to. 它的工作原理。 So, my question is: Can I do the same with only one query? 因此,我的问题是: 我可以只执行一个查询吗?

I hope I was clear in my explanation and I would appreciate any help. 我希望我的解释很清楚,希望能对您有所帮助。 Thanks in advance. 提前致谢。

Below SQL would help you get started, which will return all the rows which are higher or lower than selected id eg here for id = 6 下面的SQL将帮助您入门,它将返回高于或低于选定ID的所有行,例如此处ID = 6

SELECT id_size 
FROM sizes 
WHERE (cm_min < 60 or  cm_min > 62) and
(cm_max < 60 or cm_max > 62);

SqlFiddle Demo SqlFiddle演示

Update - Example 更新-示例

Below I have provided more closer example to your need: Remove LIMIT 1 if you need all the records, lower and higher 下面,我提供了更接近您需求的示例:如果需要所有记录(上下限),请删除LIMIT 1

SELECT id_size , 'lower'
FROM sizes 
WHERE (cm_min < 12 AND cm_max < 12)  
LIMIT 1
UNION
SELECT id_size , 'HIGHER'
FROM sizes 
WHERE (cm_min > 14 AND cm_max > 14)
LIMIT 1

SqlFiddle Demo SqlFiddle演示

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

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