可能重复:
不使用 select * 的原因是什么?
你能解释一下select_expr
语句中的哪个子句SELECT
有好处吗?我一直这样*
用select_expr
SELECT * FROM table_name WHERE ...
这已经足够了。
可能重复:
不使用 select * 的原因是什么?
你能解释一下select_expr
语句中的哪个子句SELECT
有好处吗?我一直这样*
用select_expr
SELECT * FROM table_name WHERE ...
这已经足够了。
一个比其他例子更重要的例子:
您需要使用聚合函数:
SELECT ID, COUNT(*) AS Num_Total
FROM OrderItem
GROUP BY OrderID;
您需要从 UNION 查询的两个部分获取信息。我最近在回答另一个问题时使用了它:
SELECT v1.ID AS OrderID_1, v1.NA AS NS, v2.ID AS OrderID_2, v2.NB AS NL, v3.NC AS NC
FROM (SELECT ID, COUNT(*) AS NA
FROM OrderItem
WHERE OrderID = <specified order ID>
GROUP BY OrderID
) AS v1
JOIN (SELECT ID, COUNT(*) AS NB
FROM OrderItem
WHERE OrderID != <specified order ID>
GROUP BY OrderID
) AS v2
ON v1.NA <= v2.NB
JOIN (SELECT I1.ID, COUNT(*) AS NC
FROM OrderItem AS I1
JOIN OrderItem AS I2 ON I2.ItemID = I1.ItemID AND I2.OrderID = <specified order ID>
WHERE I1.OrderID != <specified order ID>
GROUP BY I1.ID
) AS v3
ON v3.ID = v2.ID
UNION
SELECT v2.ID AS OrderID_1, v2.NB AS NS, v1.ID AS OrderID_2, v2.NA AS NL, v3.NC AS NC
FROM (SELECT ID, COUNT(*) AS NA
FROM OrderItem
WHERE OrderID = <specified order ID>
GROUP BY OrderID
) AS v1
JOIN (SELECT ID, COUNT(*) AS NB
FROM OrderItem
WHERE OrderID != <specified order ID>
GROUP BY OrderID
) AS v2
ON v1.NA > v2.NB
JOIN (SELECT I1.ID, COUNT(*) AS NC
FROM OrderItem AS I1
JOIN OrderItem AS I2 ON I2.ItemID = I1.ItemID AND I2.OrderID = <specified order ID>
WHERE I1.OrderID != <specified order ID>
GROUP BY I1.ID
) AS v3
ON v3.ID = v1.ID
在该查询中,Quantity
OrderItem 表中的列与我正在执行的计算没有任何关系。如果不使用“select_expr”而不是“SELECT *”,就无法编写该查询。您可能会注意到,最初的“聚合函数”建议是这个较大查询中的子查询之一(它出现了两次——您相信优化器会准确优化)。
有几个原因:
select a, b, a+b FROM table
补充第一点和第二点:特别是通常需要列限制。
添加到第四点:在进行临时查询时,我几乎总是使用*
. 但是程序应该总是枚举列。这可以防止令人惊讶的列重新排序,并且还可以明确实际使用了哪些数据。
想象一下,您的表有一百万列,您只对其中一个感兴趣,并且您正在通过网络通过 30 波特连接与您的数据库通信。