我正在尝试根据主键列以降序查询表。
以下是查询:
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;
我希望此查询以降序返回行。但是它没有按预期工作。我觉得DESC没有应用于查询。 我以这种方式编写查询的原因是,我想在我的Java代码中使用此查询,它将参数化函数如:
public void myFunction(String dbName, String tableName);
因为在运行时我不知道表的主键是什么。但是我只提供2个参数dbname和tablename。因此,使用以下子查询获取主键列名称:
( SELECT `COLUMN_NAME`
FROM `information_schema`.`COLUMNS`
WHERE (`TABLE_SCHEMA` = 'fdmsus_demo')
AND (`TABLE_NAME` = 'vitalstats')
AND (`COLUMN_KEY` = 'PRI')
)
以上查询相当于:
SELECT * FROM fdmsus_demo.vitalstats ORDER BY VitalsMasterKey DESC LIMIT 10;
返回的结果按预期降序排列。
任何人都可以帮我纠正查询并按降序输出。任何帮助将不胜感激。
感谢。
答案 0 :(得分:0)
尝试将desc应用于内部查询。
答案 1 :(得分:0)
试试这个会起作用
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;
答案 2 :(得分:0)
您必须编写准备声明
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;
答案 3 :(得分:-1)
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;
这应该做。您缺少需要在内部查询中应用desc函数。