限制 MySQL 中跨表的结果总数?
mysqlmysqli database
为此,您可以使用 UNION ALL 和 LIMIT 概念。在我们的示例中,我们将创建三个表。
让我们创建第一个表 −
mysql> create table demo3 −> ( −> value int −> ); Query OK, 0 rows affected (1.39 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into demo3 values(10); Query OK, 1 row affected (0.13 sec) mysql> insert into demo3 values(20); Query OK, 1 row affected (0.08 sec) mysql> insert into demo3 values(30); Query OK, 1 row affected (0.08 sec)
使用 select 语句显示表中的记录 −
mysql> select *from demo3;
这将产生以下输出 −
+-------+ | value | +-------+ | 10 | | 20 | | 30 | +-------+ 3 rows in set (0.00 sec)
创建第二个表的查询如下 −
mysql> create table demo4 −> ( −> value1 int −> ); Query OK, 0 rows affected (2.10 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into demo4 values(40); Query OK, 1 row affected (0.10 sec) mysql> insert into demo4 values(10); Query OK, 1 row affected (0.09 sec) mysql> insert into demo4 values(60); Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的记录 −
mysql> select *from demo4;
这将产生以下输出 −
+--------+ | value1 | +--------+ | 40 | | 10 | | 60 | +--------+ 3 rows in set (0.00 sec)
这是创建第三个表的查询。
mysql> create table demo5 −> ( −> value2 int −> ); Query OK, 0 rows affected (2.13 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into demo5 values(100); Query OK, 1 row affected (0.09 sec) mysql> insert into demo5 values(60); Query OK, 1 row affected (0.14 sec) mysql> insert into demo5 values(50); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的记录 −
mysql> select *from demo5;
这将产生以下输出 −
+--------+ | value2 | +--------+ | 100 | | 60 | | 50 | +--------+ 3 rows in set (0.00 sec)
以下是限制表中结果总数的查询 −
mysql> select tbl.* −> from ((select * from demo3 ORDER BY value DESC LIMIT 2 −> ) UNION ALL −> (select * from demo4 ORDER BY value1 DESC LIMIT 2 −> ) UNION ALL −> (select * from demo5 ORDER BY value2 DESC LIMIT 2 −> ) −> ) tbl −> −> LIMIT 2;
这将产生以下输出 −
+-------+ | value | +-------+ | 30 | | 20 | +-------+ 2 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/
打印
下一节:MySQL Error ERROR 1099 (HY000): Table was locked with a READ lock and can't be updated ❯❮ 上一节:MySQL 中带有 ORDER BY 的多个 LIKE 运算符?

