社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

插入到mysql的非插入

Tom • 3 年前 • 1114 次点击  

我在下面的语句中插入了mysql。当我单独运行select语句时,它会产生结果。

下面是表的Create语句

**create table if not exists analyze_checks(dbname varchar(50),table_name  varchar(50),frag_ratio decimal, days integer,needs_optimization char(3),needs_analyzing char(3)) ENGINE=INNODB**
**insert into analyze_checks(dbname,table_name,frag_ratio, days,needs_optimization,needs_analyzing ) 
(select 
'test' as dbname,
table_name,
frag_ratio,
days,
needs_optimization,
needs_analyzing
from 
(select 
table_name, 
cast(frag_ratio as decimal(5,2)) as frag_ratio, 
days,
case when frag_ratio > 1 then 'Yes' else 'No' end as needs_optimization,    
case when days > -1 then 'Yes' else 'No' end as needs_analyzing 
from (
select  
t.ENGINE,   
concat(t.TABLE_SCHEMA, '.', t.TABLE_NAME) as table_name,    
round(t.DATA_FREE/1024/1024, 2) as data_free,   
(t.data_free/(t.index_length+t.data_length)) as frag_ratio,  
datediff(now(), last_update) as days 
FROM information_schema.tables t 
left join mysql.innodb_table_stats s on t.table_name=s.table_name 
WHERE DATA_FREE > 0 ORDER BY frag_ratio DESC )d ) d 
where needs_optimization='Yes' or needs_analyzing='Yes');**
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131595
 
1114 次点击  
文章 [ 1 ]  |  最新文章 3 年前
matigo
Reply   •   1 楼
matigo    4 年前

不需要包装用于 INSERT 括号内。见鬼,整个查询可以简化如下:

INSERT INTO analyze_checks(dbname,table_name,frag_ratio, days,needs_optimization,needs_analyzing ) 
SELECT 'test' AS dbname,
       tmp.table_name, 
       CAST(tmp.frag_ratio AS DECIMAL(5,2)) AS frag_ratio, 
       tmp.days,
       CASE WHEN tmp.frag_ratio > 1 THEN 'Yes' ELSE 'No' END AS needs_optimization,    
       CASE WHEN tmp.days > -1 THEN 'Yes' ELSE 'No' END as needs_analyzing 
  FROM (SELECT CONCAT(t.TABLE_SCHEMA, '.', t.TABLE_NAME) AS table_name,    
               ROUND(t.DATA_FREE/1024/1024, 2) AS data_free,   
               (t.data_free / (t.index_length + t.data_length)) AS frag_ratio,  
               DATEDIFF(NOW(), last_update) AS days 
          FROM information_schema.tables t LEFT JOIN mysql.innodb_table_stats s ON t.table_name = s.table_name 
         WHERE DATA_FREE > 0) tmp
 WHERE 'Yes' = CASE WHEN tmp.frag_ratio > 1 THEN 'Yes' 
                    WHEN tmp.days > -1 THEN 'Yes'
                    ELSE 'No' END
 ORDER BY frag_ratio DESC;

适当使用括号和衍生表格即可