SELECT
CONCAT_WS(' ', lastName, firstname) `Full name`
FROM
employees
ORDER BY
`Full name`;
执行上面代码,得到以下结果 -
mysql> SELECT
CONCAT_WS(' ', lastName, firstname) `Full name`
FROM
employees
ORDER BY
`Full name`;
+-------------------+
| Full name |
+-------------------+
| Bondur Gerard |
| Bondur Loui |
| Bott Larry |
| Bow Anthony |
| Castillo Pamela |
| Firrelli Jeff |
| Firrelli Julie |
| Fixter Andy |
| Gerard Martin |
| Hernandez Gerard |
| Jennings Leslie |
| Jones Barry |
| Kato Yoshimi |
| King Tom |
| Marsh Peter |
| Murphy Diane |
| Nishi Mami |
| Patterson Mary |
| Patterson Steve |
| Patterson William |
| Thompson Leslie |
| Tseng Foon Yue |
| Vanauf George |
+-------------------+
23 rows in set
以下语句查询总金额大于60000的订单。它在GROUP BY和HAVING子句中使用列别名。
SELECT
orderNumber `Order no.`,
SUM(priceEach * quantityOrdered) total
FROM
orderdetails
GROUP BY
`Order no.`
HAVING
total > 60000;
执行上面查询语句,得到以下结果 -
mysql> SELECT
orderNumber `Order no.`,
SUM(priceEach * quantityOrdered) total
FROM
orderdetails
GROUP BY
`Order no.`
HAVING
total > 60000;
+-----------+----------+
| Order no. | total |
+-----------+----------+
| 10165 | 67392.85 |
| 10287 | 61402.00 |
| 10310 | 61234.67 |
+-----------+----------+
3 rows in set
Error Code: 1052. Column 'customerNumber' in on clause is ambiguous
为避免此错误,应该使用表别名来限定customerNumber列:
SELECT
customerName,
COUNT(o.orderNumber) total
FROM
customers c
INNER JOIN orders o ON c.customerNumber = o.customerNumber
GROUP BY
customerName
HAVING total >=5
ORDER BY
total DESC;
执行上面查询语句,得到以下结果 -
mysql> SELECT
customerName,
COUNT(o.orderNumber) total
FROM
customers c
INNER JOIN orders o ON c.customerNumber = o.customerNumber
GROUP BY
customerName
HAVING total >=5
ORDER BY
total DESC;
+------------------------------+-------+
| customerName | total |
+------------------------------+-------+
| Euro+ Shopping Channel | 26 |
| Mini Gifts Distributors Ltd. | 17 |
| Reims Collectables | 5 |
| Down Under Souveniers, Inc | 5 |
| Danish Wholesale Imports | 5 |
| Australian Collectors, Co. | 5 |
| Dragon Souveniers, Ltd. | 5 |
+------------------------------+-------+
7 rows in set
SELECT
customers.customerName,
COUNT(orders.orderNumber) total
FROM
customers
INNER JOIN orders ON customers.customerNumber = orders.customerNumber
GROUP BY
customerName
ORDER BY
total DESC