遇到 MySQL ONLY_FULL_GROUP_BY
錯誤? 本指南為 MySQL 新手和經驗豐富的使用者提供了清晰的解釋和實用的解決方案。
ONLY_FULL_GROUP_BY
ONLY_FULL_GROUP_BY
是強制執行標準 GROUP BY
行為的 MySQL 設定。 啟用此設定後,您的 SELECT
語句必須遵守以下規則:
SELECT
中的所有欄位都必須位於 GROUP BY
中: 所選的每個欄位也必須包含在 GROUP BY
子句中。 GROUP BY
中的欄位需要聚合函數(例如,COUNT
、SUM
、AVG
、MAX
、MIN
)。 GROUP BY
子句中的欄位。 考慮一個名為orders
的表:
<code class="language-sql">CREATE TABLE orders ( id INT, customer_name VARCHAR(100), product VARCHAR(100), amount DECIMAL(10,2) ); INSERT INTO orders VALUES (1, 'John', 'Laptop', 1000), (2, 'John', 'Mouse', 20), (3, 'Mary', 'Keyboard', 50), (4, 'Mary', 'Monitor', 200);</code>
此查詢將觸發錯誤:
<code class="language-sql">SELECT customer_name, product, SUM(amount) FROM orders GROUP BY customer_name;</code>
問題? product
已選取但未分組。 MySQL 無法確定為每個客戶顯示哪個產品(因為他們可能購買了多個商品)。
解決方案1:修改MySQL設定
快速修復(會話等級):
<code class="language-sql">SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));</code>
永久修復(全域等級):
<code class="language-sql">SET GLOBAL sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';</code>
解決方案 2:調整您的查詢
GROUP BY
中的所有欄位:<code class="language-sql">SELECT customer_name, product, SUM(amount) FROM orders GROUP BY customer_name, product;</code>
MAX
、MIN
):<code class="language-sql">SELECT customer_name, MAX(product) as product, SUM(amount) as total_amount FROM orders GROUP BY customer_name;</code>
<code class="language-sql">SELECT o.* FROM orders o INNER JOIN ( SELECT customer_name, SUM(amount) as total_amount FROM orders GROUP BY customer_name ) grouped ON o.customer_name = grouped.customer_name;</code>
<code class="language-sql">SELECT category, MAX(product_name) as top_product, COUNT(*) as total_orders, SUM(amount) as total_sales FROM sales GROUP BY category;</code>
<code class="language-sql">SELECT customer_id, MIN(first_name) as first_name, MIN(last_name) as last_name, COUNT(*) as total_purchases, SUM(purchase_amount) as total_spent, AVG(purchase_amount) as avg_purchase_amount FROM customer_purchases GROUP BY customer_id;</code>
缺少唯一 ID: 錯誤:SELECT id, customer_name, COUNT(*) FROM orders GROUP BY customer_name;
正確:SELECT MIN(id) as first_order_id, customer_name, COUNT(*) FROM orders GROUP BY customer_name;
複雜聯結:使用 GROUP BY
聯結時請仔細考慮聚合。 適當使用聚合函數或使用子查詢重構查詢。
ONLY_FULL_GROUP_BY
以提高查詢準確性並遵守 SQL 標準。 SELECT @@sql_mode;
SHOW VARIABLES LIKE 'sql_mode';
SHOW GRANTS;
ONLY_FULL_GROUP_BY
啟用雖然禁用它很誘人,但請考慮在新專案中保持 ONLY_FULL_GROUP_BY
處於活動狀態,遵守 SQL 標準,並防止微妙的查詢錯誤。
ONLY_FULL_GROUP_BY
錯誤雖然最初令人沮喪,但鼓勵更好的查詢設計。 了解其目的並實施正確的解決方案將提高您的 MySQL 技能和程式碼可維護性。 優先考慮準確的資料選擇和適當的聚合函數。快樂編碼!
以上是MySQL ONLY_FULL_GROUP_BY 錯誤:簡單修復和最佳實踐的詳細內容。更多資訊請關注PHP中文網其他相關文章!