MySQL order by primary key

前端 未结 2 1481
梦如初夏
梦如初夏 2021-02-08 07:30

Some SQL servers allow for a generic statement such as ORDER BY PRIMARY KEY. I don\'t believe this works for MySQL, is there any such workaround that would allow f

2条回答
  •  再見小時候
    2021-02-08 07:53

    MySQL generally pulls data out by insertion order which would be by primary key, but that aside you technically can do the same thing if you pull out the primary key column name and put it in an order by

    SELECT whatever FROM table
    ORDER BY
    (   SELECT `COLUMN_NAME`
        FROM `information_schema`.`COLUMNS`
        WHERE (`TABLE_SCHEMA` = 'dbName')
          AND (`TABLE_NAME` = 'tableName')
          AND (`COLUMN_KEY` = 'PRI')
    );
    

    For composite keys you can use this

    SELECT whatever FROM table
    ORDER BY
    (   SELECT GROUP_CONCAT(`COLUMN_NAME` SEPARATOR ', ')
        FROM `information_schema`.`COLUMNS`
        WHERE (`TABLE_SCHEMA` = 'dbName')
          AND (`TABLE_NAME` = 'tableName')
          AND (`COLUMN_KEY` = 'PRI')
    );
    

    Permission for information schema access from the DOCS

    Each MySQL user has the right to access these tables, but can see only the rows in the tables that correspond to objects for which the user has the proper access privileges. In some cases (for example, the ROUTINE_DEFINITION column in the INFORMATION_SCHEMA.ROUTINES table), users who have insufficient privileges see NULL. These restrictions do not apply for InnoDB tables; you can see them with only the PROCESS privilege.

    The same privileges apply to selecting information from INFORMATION_SCHEMA and viewing the same information through SHOW statements. In either case, you must have some privilege on an object to see information about it.

    SETUP:

    CREATE TABLE some_stuff (
        firstID INT,
        secondID INT,
        username varchar(55),
        PRIMARY KEY (firstID, secondID)
    ) ;
    

    QUERY:

    SELECT GROUP_CONCAT(`COLUMN_NAME` SEPARATOR ', ')
    FROM `information_schema`.`COLUMNS`
    WHERE (`TABLE_SCHEMA` = 'dbName')
      AND (`TABLE_NAME` = 'some_stuff')
      AND (`COLUMN_KEY` = 'PRI');
    

    OUTPUT:

    +--------------------------------------------+
    | GROUP_CONCAT(`COLUMN_NAME` SEPARATOR ', ') |
    +--------------------------------------------+
    |              firstID, secondID             |
    +--------------------------------------------+
    

提交回复
热议问题