how to select data between a range

2

As I can build the SELECT, to select from a table the data that are in the middle of a sequence, I need to select from the column code, the data in the sequence are between the smallest code, ie 001, and the last Bone 005, knowing that 005 could increase with a new record.

BD

id | nombre | codigo |
---------------------
1  | Maria  | 005    |
---------------------
2  | Jose   | 004    |
---------------------
3  | Pedro  | 001    |
---------------------
4  | Marta  | 003    |
---------------------
5  | Juan   | 002    |
---------------------

PHP

$query_datos = "SELECT * FROM tabla1";
    
asked by Mateo 29.07.2018 в 01:32
source

2 answers

0

Replicating your exercise, I propose the following solution

mysql> CREATE TABLE s(
    -> id BIGINT PRIMARY KEY AUTO_INCREMENT,
    -> name VARCHAR(100),
    -> codigo INT(3) UNSIGNED ZEROFILL NOT NULL);
Query OK, 0 rows affected (0.77 sec)


mysql> insert into s(name, codigo)
    -> values("maria", 005),
    -> ("jose", 004),
    -> ("pedro", 001),
    -> ("marta", 003),
    -> ("juan", 002);
Query OK, 5 rows affected (0.17 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM s;
+----+-------+--------+
| id | name  | codigo |
+----+-------+--------+
|  1 | maria |    005 |
|  2 | jose  |    004 |
|  3 | pedro |    001 |
|  4 | marta |    003 |
|  5 | juan  |    002 |
+----+-------+--------+
5 rows in set (0.00 sec)

mysql> SELECT id, name, codigo FROM s WHERE codigo < 5 AND codigo > 1;
+----+-------+--------+
| id | name  | codigo |
+----+-------+--------+
|  2 | jose  |    004 |
|  4 | marta |    003 |
|  5 | juan  |    002 |
+----+-------+--------+
3 rows in set (0.04 sec)
  

Where I use the comparison operators mayor que(>) and menor que(<)   to set the range of values you want to filter; in addition to   As in your exercise you need to filter by 2 values, I use the   LOGICAL OPERATOR AND that establishes the need for both   conditions are true; both the extreme left as well as the   from the far right

So your query should also work

mysql> SELECT id, name, codigo FROM s WHERE codigo > 1 AND codigo < 5;

In PHP

$query_datos = "SELECT * FROM tabla1 WHERE $codigo > 1 AND $codigo < 5";

I add the logical operators and their syntax

Operador NOT y su equivalente es !

Operador AND y su equivalente &&

Operador OR y su equivalente ||
    
answered by 29.07.2018 в 02:13
0

You can try the following:

SELECT
    id, name, codigo
FROM
    tabla1
WHERE
    codigo > (SELECT MIN(codigo) FROM tabla1)
AND codigo < (SELECT MAX(codigo) FROM tabla1);
    
answered by 29.07.2018 в 03:11