用复杂字符串从mysql中获取两个区间的数据

mm5n2pyu  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(322)

员工表

Id  Name Salary frame
1   A    5000   MDF-125NH
2   b    10000  MDF-025AH
3   c    15000  MDF-325KH
4   d    20000  MDF-425LH
5   e    25000  MDF-521MH

我想从mysql获取到帧之间的数据,即(mdf-125nh,mdf-325kh)。
我尝试了一些东西,但没有成功。

SELECT DISTINCT (id) AS ln
FROM employee c04 BETWEEN (
    SELECT SUBSTRING(frame, 0, CHARINDEX('-', frame))
    FROM employee
    ) AND (
    SELECT SUBSTRING(frame, 0, CHARINDEX('-', frame))
    FROM employee
    ) )

SELECT DISTINCT (id) AS ln
FROM employee c04 BETWEEN (
    SELECT SUBSTRING("MDF-125NH", 0, CHARINDEX('-', "MDF-125NH"))
    FROM employee
    ) AND (
    SELECT SUBSTRING("MDF-325KH", 0, CHARINDEX('-', "MDF-325KH"))
    FROM employee
    ) )
olhwl3o2

olhwl3o21#

CREATE TABLE employee(
   Id     INTEGER  NOT NULL PRIMARY KEY 
  ,Name   VARCHAR(1) NOT NULL
  ,Salary INTEGER  NOT NULL
  ,frame  VARCHAR(9) NOT NULL
);
INSERT INTO employee(Id,Name,Salary,frame) VALUES (1,'A',5000,'MDF-125NH');
INSERT INTO employee(Id,Name,Salary,frame) VALUES (2,'b',10000,'MDF-025AH');
INSERT INTO employee(Id,Name,Salary,frame) VALUES (3,'c',15000,'MDF-325KH');
INSERT INTO employee(Id,Name,Salary,frame) VALUES (4,'d',20000,'MDF-425LH');
INSERT INTO employee(Id,Name,Salary,frame) VALUES (5,'e',25000,'MDF-521MH');

SELECT *
FROM employee 
WHERE frame BETWEEN 'MDF-125NH' and 'MDF-325KH'
;

结果如下:

+----+----+------+--------+-----------+
|    | Id | Name | Salary |   frame   |
+----+----+------+--------+-----------+
|  1 |  1 | A    |   5000 | MDF-125NH |
|  2 |  3 | c    |  15000 | MDF-325KH |
+----+----+------+--------+-----------+

sql中的“between”具有非常具体的含义,相当于:

frame >= 'MDF-125NH' and frame <= 'MDF-325KH'

这个定义可能不一定与你所期望的一致。

+----+----+------+--------+-----------+
|    | Id | Name | Salary |   frame   |
+----+----+------+--------+-----------+
|  1 |  1 | A    |   5000 | MDF-125NH |
|  2 |  2 | b    |  10000 | MDF-025AH | << is this the "between" you want?
|  3 |  3 | c    |  15000 | MDF-325KH |
|  4 |  4 | d    |  20000 | MDF-425LH |
|  5 |  5 | e    |  25000 | MDF-521MH |
+----+----+------+--------+-----------+

此查询:

SELECT *
FROM employee 
WHERE id BETWEEN (select min(id) from employee where frame IN ('MDF-125NH','MDF-325KH')) 
         AND (select max(id) from employee where frame IN ('MDF-125NH','MDF-325KH'))
;

产生以下结果:

+----+----+------+--------+-----------+
|    | Id | Name | Salary |   frame   |
+----+----+------+--------+-----------+
|  1 |  1 | A    |   5000 | MDF-125NH |
|  2 |  2 | b    |  10000 | MDF-025AH |
|  3 |  3 | c    |  15000 | MDF-325KH |
+----+----+------+--------+-----------+

看到这个了吗

相关问题