MySQL order by primary key dynamically in DESC order

╄→гoц情女王★ 提交于 2019-12-25 09:29:31

问题


I am trying to query a table in descending order based on its primary key column.

Here is the query:

SELECT * FROM fdmsus_demo.vitalstats
ORDER BY 
( SELECT `COLUMN_NAME`
FROM `information_schema`.`COLUMNS`
WHERE (`TABLE_SCHEMA` = 'fdmsus_demo')
  AND (`TABLE_NAME` = 'vitalstats')
  AND (`COLUMN_KEY` = 'PRI') 
 ) DESC LIMIT 10; 

I am expecting this query to return rows in descending order. However it is not working as expected. I feel DESC is not being applied to the query. The reason I am writing query in this fashion is, I wanted to use this query in my Java code and it will parameterized function like:

public void myFunction(String dbName, String tableName);

Because at run time I will not be knowing what will be the primary key of a table. However I am supplying only 2 parameters dbname and tablename. Hence fetching primary key column name using following sub-query:

( SELECT `COLUMN_NAME`
FROM `information_schema`.`COLUMNS`
WHERE (`TABLE_SCHEMA` = 'fdmsus_demo')
  AND (`TABLE_NAME` = 'vitalstats')
  AND (`COLUMN_KEY` = 'PRI') 
 )

Above query is equivalent to:

SELECT * FROM fdmsus_demo.vitalstats ORDER BY VitalsMasterKey DESC LIMIT 10;

Which returns result in descending order as expected.

Can anyone please help me in correcting the query and get output in descending order. Any help will be appreciated.

Thanks.


回答1:


Try applying desc to inner query .




回答2:


Try this it will work

set @Query1=Concat('SELECT * FROM fdmsus_demo.vitalstats ORDER BY ', (SELECT `COLUMN_NAME`
    FROM `information_schema`.`COLUMNS`
    WHERE (`TABLE_SCHEMA` = 'fdmsus_demo')
      AND (`TABLE_NAME` = 'vitalstats')
      AND (`COLUMN_KEY` = 'PRI')),' desc limit 10');

 PREPARE stmt FROM @Query1; 
 EXECUTE stmt;  



回答3:


You have to write prepare statement

SET @col = '';
SELECT `COLUMN_NAME` INTO @col
FROM `information_schema`.`COLUMNS`
WHERE (`TABLE_SCHEMA` = 'fdmsus_demo')
  AND (`TABLE_NAME` = 'vitalstats')
  AND (`COLUMN_KEY` = 'PRI');
SET @q = CONCAT('SELECT * FROM fdmsus_demo.vitalstats ORDER BY ',@col,' DESC LIMIT 10');
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;



回答4:


SELECT * FROM fdmsus_demo.vitalstats
ORDER BY 
( SELECT `COLUMN_NAME`
FROM `information_schema`.`COLUMNS`
WHERE (`TABLE_SCHEMA` = 'fdmsus_demo')
  AND (`TABLE_NAME` = 'vitalstats')
  AND (`COLUMN_KEY` = 'PRI') 
ORDER BY COLUMN_NAME DESC LIMIT 10;
) ORDER BY COLUMN_NAME DESC LIMIT 10;

This should do. You are missing on which you need to apply desc function in the inner query.



来源:https://stackoverflow.com/questions/44646523/mysql-order-by-primary-key-dynamically-in-desc-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!