一尘不染

从MySQL选择表的最后N#列

sql

我有超过35列的表,前20列是固定的,并且每个表中的列号都不同。我需要从表中选择最后10列,例如,我该如何实现?就像此查询返回前20条记录

select * from table1 limit 10;

我想对列执行相同的操作,即在查询中返回列名称,然后在其他查询中使用这些名称,例如:

SELECT (SELECT column_name FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = 'table1' ) FROM table1;

阅读 249

收藏
2021-03-10

共1个答案

一尘不染

您可以通过准备好的语句来实现。您的查询将如下所示:

SELECT 
  CONCAT('SELECT ', 
         GROUP_CONCAT(COLUMN_NAME), 
         ' FROM test') 
FROM 
  (SELECT 
    COLUMN_NAME, 
    ORDINAL_POSITION 
  FROM 
    INFORMATION_SCHEMA.COLUMNS 
  WHERE 
    TABLE_SCHEMA='test' 
    AND 
    TABLE_NAME='test' 
  ORDER BY 
    ORDINAL_POSITION DESC LIMIT 10) AS ord_desc 
ORDER BY 
  ord_desc.ORDINAL_POSITION

-这将创建一个内容如下的SQL:

选择日期,标题来自测试

(在样品上方我不得不选择在2列中,可在该部分进行调整:ORDER BY ORDINAL_POSITION DESC LIMIT 10

因此,您所需要做的就是准备此语句。就我而言:

SQL:

mysql> set @ sql =(SELECT CONCAT('SELECT',GROUP_CONCAT(COLUMN_NAME),'FROM test')FROM(SELECT COLUMN_NAME,ORDINAL_POSITION FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA ='test'和TABLE_NAME ='test'ORDER BY ORDINAL_POSITION DESC LIMIT 2)AS ord_desc ORDER BY ord_desc.ORDINAL_POSITION);
查询正常,受影响的0行(0.02秒)

准备:

mysql>从@sql准备stmt;
查询正常,受影响的0行(0.00秒)

结果:

mysql> execute stmt;
+------------+--------------+
| date       | title        |
+------------+--------------+
| 2014-02-04 | my event 001 |
| 2014-02-04 | my event 002 |
| 2014-02-05 | my event 003 |
| 2014-02-05 | my event 004 |
| 2014-02-05 | my event 005 |
| 2014-02-07 | my event 006 |
| 2014-02-07 | my event 007 |
+------------+--------------+
7 rows in set (0.00 sec)
2021-03-10