mysql dual使用

在编写sql语句时,dual表可以作为一个空表在任意场合使用。
例:

select 7 * 9 from dual;   # 计算器
+-----+
| 7*9 |
+-----+
|  63 |
+-----+

这样做是为了保持sql语句的书写习惯。以下写法也可以实现相同效果:

select 7 * 9 
+-----+
| 7*9 |
+-----+
|  63 |
+-----+

但如果要附加条件,那就必须要带上dual

# success
select 7 * 9 from dual where exists(selec 1 from student where id=10);
+-----+
| 7*9 |
+-----+
|  63 |
+-----+

# failed
select 7 * 9 where exists(selec 1 from student where id=10);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where exists (select 1 from student where id=10)' at line 1

mysql文档中对于dual表的解释:

You are allowed to specify DUAL as a dummy table name in situations
where no tables are referenced

你可以在没有表的情况下指定一个虚拟的表名 mysql> SELECT 1 + 1 FROM DUAL;

DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and possibly other clauses. MySQL may ignore the clauses. MySQL does not require FROM DUAL if no tables are referenced.

DUAL是为了方便那些要求所有SELECT语句都应该具有FROM和其他子句的人。MySQL可能会忽略该条款。如果没有引用表,MySQL不需要从DUAL。

posted @   马猴♂兄贵  阅读(33)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示