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

mysqlmysqli database

为此,您可以使用 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

相关文章