MySQL 5.7 版,啟用 ONLY_FULL_GROUP_BY
對于每個結果event_id IN (4610, 4609, 4608, 4607, 4606, 4605, 4604, 4603, 4602, 4601),需要計算LIMIT 1(或MIN(id)),獲取id計算字串的值。作為整個請求的結果,我們得到一個 的串列id,從中我們得到一個 的串列image。PS 的值image非常大,所以不能直接互動。這是一個有效的查詢,但執行起來很慢!我需要寫不同的,我不明白怎么寫。
SELECT id, event_id, image
FROM eventImages
WHERE id IN (
SELECT MIN(id)
FROM eventImages WHERE event_id IN (4610, 4609, 4608, 4607, 4606, 4605, 4604, 4603, 4602, 4601)
GROUP BY event_id
)
ORDER BY event_id DESC;
create table eventImages
(
id int auto_increment
primary key,
uuid varchar(36) null,
event_id int null,
image mediumtext null
);
uj5u.com熱心網友回復:
在 MySQL 5.7 中,您應該使用INNER JOINin 代替WHERE ... IN子句,正如 @Akina 在評論部分中已經建議的那樣。這將有所改進,因為WHERE ... IN無法利用索引(確保在“ eventImages.id ”欄位上使用和索引)。
SELECT id, event_id, image
FROM eventImages
INNER JOIN (SELECT MIN(id) AS id
FROM eventImages
WHERE event_id BETWEEN 4601 AND 4610
GROUP BY event_id) subquery
ON eventImages.id = subquery.id
ORDER BY event_id DESC;
另一種選擇是使用變數生成排名值。然后我們可以創建一個布林值(0/1),僅當觀察到 event_id 的變化時才觸發為 1(這樣我們只為每個“ event_id ”值取第一個 id)。
SET @curr_event_id = '';
SELECT event_id, id, image
FROM (SELECT IF(event_id <> @curr_event_id, 1, 0) AS rn,
IF(event_id <> @curr_event_id,
@curr_event_id := event_id,
event_id ) AS event_id,
id,
image
FROM tab
ORDER BY event_id, id) subquery
WHERE rn = 1
在 MySQL 8.0 中,不要自行加入表,而是嘗試使用ROW_NUMBER視窗函式并應用過濾,如下所示:
WITH cte AS (
SELECT id, ROW_NUMBER() OVER(PARTITION BY event_id ORDER BY id) AS rn
FROM eventImages
WHERE event_id BETWEEN 4601 AND 4610
)
SELECT id, event_id, image
FROM eventImages
WHERE rn = 1
它將為每個“ event_id ”分配 1 到最低的“ id ” ,然后您可以過濾掉您感興趣的行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/516886.html
上一篇:腳本'D:\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle'行:1159
下一篇:比較兩個增值稅號
