MariaDB Order By子句

MariaDB Order By子句

ORDER BY 子句,如前面讨论的那样,对语句的结果进行排序。它指定了操作数据的顺序,并包括按升序(ASC)或降序(DESC)排序的选项。如果不指定排序规则,则默认为升序。

ORDER BY子句出现在各种语句中,如DELETE和UPDATE。它们总是出现在语句的末尾,而不是在子查询或设置函数之前,因为它们操作的是最终的结果表。您也不能使用整数来标识列。

请查看下面给出的ORDER BY子句的一般语法−

SELECT field, field2,... [or column] FROM table_name, table_name2,...
ORDER BY field, field2,... ASC[or DESC]

在命令提示符或PHP脚本内使用ORDER BY子句。

命令提示符

在命令提示符下,只需使用标准命令-

root@ host# mysql -u root -p password;
Enter password:*******
mysql> use PRODUCTS;
Database changed

mysql> SELECT * from products_tbl ORDER BY product_manufacturer ASC
+-------------+----------------+----------------------+
| ID_number   | Nomenclature   | product_manufacturer |
+-------------+----------------+----------------------+
| 56789       | SuperBlast 400 | LMN Corp             |
+-------------+----------------+----------------------+
| 67891       | Zoomzoom 5000  | QFT Corp             |
+-------------+----------------+----------------------+
| 12347       | Orbitron 1000  | XYZ Corp             |
+-------------+----------------+----------------------+

使用ORDER BY子句的PHP脚本

再次利用 mysql_query() 函数,在使用ORDER BY子句的语句中使用。

<?php
   dbhost = 'localhost:3036';dbuser = 'root';
   dbpass = 'rootpassword';conn = mysql_connect(dbhost,dbuser, dbpass);

   if(!conn ) {
      die('Could not connect: ' . mysql_error());
   }

   sql = 'SELECT product_id, product_name, product_manufacturer, ship_date      FROM products_tbl ORDER BY product_manufacturer DESC';

   mysql_select_db('PRODUCTS');retval = mysql_query( sql,conn );

   if(! retval ) {
      die('Could not get data: ' . mysql_error());
   }

   while(row = mysql_fetch_array(retval, MYSQL_ASSOC)) {
      echo "Product ID :{row['product_id']} <br> ".
         "Name: {row['product_name']} <br> ".
         "Manufacturer: {row['product_manufacturer']} <br> ".
         "Ship Date : {row['ship_date']} <br> ".
         "--------------------------------<br>";
   }

   echo "Fetched data successfully\n";
   mysql_close(conn);
?>

在成功检索数据时,您将看到以下输出−

Product ID: 12347
Nomenclature: Orbitron 1000
Manufacturer: XYZ Corp
Ship Date: 01/01/17
----------------------------------------------
Product ID: 67891
Nomenclature: Zoomzoom 5000
Manufacturer: QFT Corp
Ship Date: 01/01/17
----------------------------------------------
Product ID: 56789
Nomenclature: SuperBlast 400
Manufacturer: LMN Corp
Ship Date: 01/04/17
----------------------------------------------
mysql> Fetched data successfully

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程