The innermost query executes first. Its parent query executes last so it can use the results returned by inner queries.
For a subquery to compare multiple columns, those columns must be selected in the main query.
A subquery can’t be nested in a SET command because it is used with UPDATE to adjust specific columns and values in a table.
To return more than one row, subqueries must contain multiple value operators such as the IN command.
Subqueries that return more than one row rely on multiple value operators such as the IN command.
CASE: Returns records with your conditions by allowing you to include if/then statements in your query
Aliasing: When you temporarily name a table or column in your query to make it easier to read and write
比較:
SELECT
Warehouse.warehouse_id,
Warehouse.warehouse_alias AS Warehouse_name,
COUNT(Orders.order_id) AS number_of_orders,
(
SELECT
COUNT(*)
FROM `stately-list-359606.warehouse_orders.Orders`
) AS total_orders,
FROM
`stately-list-359606.warehouse_orders.Warehouse` AS Warehouse
LEFT JOIN
`stately-list-359606.warehouse_orders.Orders` AS Orders ON
Orders.warehouse_id = Warehouse.warehouse_id
GROUP BY
Warehouse.warehouse_id,
Warehouse_name
HAVING
COUNT(Orders.order_id) >0
此從 warehouse 呼叫內容,再直接串接 orders 的 id 與 warehouse 的 id,再用 Group 去算不同的 id 分別的有幾個 orders。
SELECT
Cal.id,
Warehouse.warehouse_alias,
Cal.total_of_number,
Cal.total
FROM
(
SELECT
COUNT(*) AS total_of_number,
warehouse_id AS id,
(
SELECT
COUNT(*)
FROM `stately-list-359606.warehouse_orders.Orders`
) AS total
FROM
`stately-list-359606.warehouse_orders.Orders` AS Orders
GROUP BY
warehouse_id
) AS Cal
LEFT JOIN
`stately-list-359606.warehouse_orders.Warehouse` AS Warehouse ON
Cal.id = Warehouse.warehouse_id
此先創造一個表 Cal,裡面有先用 group 去計算同個倉庫 ID 有幾個訂單,並且先算出總訂單。最後再用 Cal 串接 Warehouse 的 id 得到 name
Note: