mysql如何快速编写单表查询语句

目录

背景

我们在编写查询语句的时候,都提倡需要用到哪些字段就查哪些字段,这样有两个好处:1、可以增加程序运行效率,2、可以避免无关字段被暴露。那我们一个字段一个字段写就比较烦,有没有方法快速生成呢?答案是有,下面就是生成的语句。

生成sql语句

sql 复制代码
#数据库
SET @databaseName:= 'shop_db';	
#表
SET @tableName := 'buyer';
#表别名
SET @alias := 't';

#生成查询语句
SELECT
	CONCAT('SELECT ',GROUP_CONCAT( CONCAT(@alias,'.'), COLUMN_NAME ORDER BY ORDINAL_POSITION ASC SEPARATOR ',' ),' FROM ',@tableName,' t') selectSql 
FROM
	information_schema.COLUMNS 
WHERE
	TABLE_SCHEMA = @databaseName 
	AND TABLE_NAME = @tableName;

生成的sql:

sql 复制代码
SELECT
	t.buyer_user_id,
	t.NAME,
	t.sex,
	t.birthday,
	t.wechat_open_id,
	t.wechat_union_id,
	t.wechat_name,
	t.wechat_number,
	t.ali_user_id,
	t.phone,
	t.PASSWORD,
	t.head_image,
	t.state,
	t.if_black,
	t.remark,
	t.token,
	t.member_level_id,
	t.growth,
	t.credit,
	t.create_time,
	t.update_time,
	t.id_kind,
	t.id_no,
	t.user_type,
	t.client_name,
	t.uid_on_branch,
	t.client_type,
	t.realname_time,
	t.hq_token,
	t.platform_account,
	t.login_ip,
	t.login_time,
	t.if_auth,
	t.source,
	t.third_customer_id,
	t.source_customer_id 
FROM
	buyer t

最后把不要的字段删除就可以了,只做减法。

相关推荐
djjjx.7 小时前
Mysql数据库基础篇(八):详细讲解复合查询、多表查询、自连接、多行、多列子查询与合并查询
数据库·mysql
CoderYanger11 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第八弹):MyBatis Generator
java·数据库·spring boot·spring·java-ee·tomcat·mybatis
MSTcheng.13 小时前
【MySQL】MySQL数据库——表的操作
数据库·mysql·adb
FungLeo13 小时前
FengCMS · PHP+MySQL 升级实录 · 内容写入一致性:锁等待超时与跨模型子树删除竞态
开发语言·mysql·php·工程实践·fengcms
Yeats_Liao13 小时前
物联网平台MongoDB实战|(一)为什么选择MongoDB
数据库·物联网·mongodb
ZhengEnCi14 小时前
覆盖索引是什么:用借书和外卖看懂回表这件事
sql·mysql·postgresql
鹤落晴春14 小时前
MySQL日志梳理
运维·数据库·mysql
五彩小白15 小时前
Redis的过期删除和内存淘汰机制
数据库·redis·缓存
学长毕设15 小时前
基于SpringBoot 博物馆文物租赁及修复管理系统-附源码
大数据·数据库·spring boot
FungLeo15 小时前
FengCMS · PHP+MySQL 升级实录 · MySQL DDL不能回滚:模型字段结构操作的失败续做
android·mysql·php·工程实践·fengcms