在 MySQL 中选择三条具有固定字符数的随机记录,每个列值具有固定字符数


为此,你可以使用 CHAR_LENGTH()。对于随机记录,使用 RAND()。让我们首先创建一个表格 −

mysql> create table DemoTable (Subject text);
Query OK, 0 rows affected (0.61 sec)

示例

使用 insert 命令向表中插入一些记录 −

mysql> insert into DemoTable values('C');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('MySQL');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Java');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('MongoDB');
Query OK, 1 row affected (0.59 sec)
mysql> insert into DemoTable values('RubyOnRails');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('C++');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Python');
Query OK, 1 row affected (0.20 sec)

使用 select 语句从表中显示所有记录 −

mysql> select *from DemoTable;

输出

+-------------+
| Subject     |
+-------------+
| C           |
| MySQL       |
| Java        |
| MongoDB     |
| RubyOnRails |
| C++         |
| Python      |
+-------------+
7 rows in set (0.00 sec)

以下是查询,用于为每个查询选择 3 条具有固定字符数的随机记录 −

mysql> select *from
(select *from DemoTable WHERE CHAR_LENGTH(Subject) = 7 ORDER BY RAND() LIMIT 1 ) tbl
UNION
(select *from DemoTable WHERE CHAR_LENGTH(Subject) = 11 ORDER BY RAND() LIMIT 1 )
UNION
(select *from DemoTable WHERE CHAR_LENGTH(Subject) = 5 ORDER BY RAND() LIMIT 1 );

输出

+-------------+
| Subject     |
+-------------+
| MongoDB     |
| RubyOnRails |
| MySQL       |
+-------------+
3 rows in set (0.04 sec

更新于: 02-Jul-2020

79 次浏览

开启你的 职业生涯

通过完成该课程获得认证

开始吧
广告