您能否解释一下select_expr
语句中的SELECT
子句有用吗?我一直在使用*
select_expr
这样
SELECT * FROM table_name WHERE ...
就够了。
答案 0 :(得分:1)
有几个原因:
select a, b, a+b FROM table
添加到第一点和第二点:特别是通常需要列限制。
添加到第四点:在进行adhoc查询时,我几乎总是使用*
。但程序应始终枚举列。这可以防止令人惊讶的列重新排序,并且还可以清楚地显示实际使用的数据。
答案 1 :(得分:1)
除了已经建议的其他例子之外的一个例子:
您需要使用聚合函数:
SELECT ID, COUNT(*) AS Num_Total
FROM OrderItem
GROUP BY OrderID;
您需要从UNION查询的两个部分获取信息。我最近在另一个问题answer中使用了这个问题:
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
该查询中没有任何一个是OrderItem表中的Quantity
列,与我正在进行的计算有任何相关性。如果不使用'select_expr'而不是'SELECT *',就无法编写该查询。您可能会注意到,初始“聚合函数”建议是此较大查询中的子查询之一(并且它出现两次 - 您相信优化程序将准确地进行优化)。
答案 2 :(得分:0)
想象一下,您的表有一百万列,您只对一个列感兴趣,并且您通过30波特连接通过网络与数据库通信。