使用用戶變量測試: -
SELECT tel, email
FROM
(
SELECT Sub1.id, Sub1.name, Sub1.tel, Sub1.email, @name:=IF(name IS NULL, @name, name) AS aName
FROM (SELECT * FROM geoname ORDER BY id) Sub1
CROSS JOIN (SELECT @name:="") Sub2
) Sub3
WHERE aName = 'geo'
由於Barmar強調,如果名字字段爲空時,在空它,而不是這僅適用於''。如果它需要應付空白以及NULL: -
SELECT tel, email
FROM
(
SELECT Sub1.id, Sub1.name, Sub1.tel, Sub1.email, @name:=IF(name IS NULL OR name = "", @name, name) AS aName
FROM (SELECT * FROM Table1 ORDER BY id) Sub1
CROSS JOIN (SELECT @name:="") Sub2
) Sub3
WHERE aName = 'geo'
有一點戲劇。挺喜歡通過Barmar的解決方案,但有一個發揮,如果我能簡化並消除了幾個子查詢的: -
SELECT a.*
FROM geoname a
INNER JOIN
(
SELECT a.id AS MinId, IFNULL(MIN(b.id), MAX(c.id)) AS MaxId
FROM geoname a
LEFT OUTER JOIN geoname b
ON a.id < b.id AND b.name IS NOT NULL
CROSS JOIN geoname c
WHERE a.name = 'geo'
GROUP BY a.id
) Sub1
ON a.id BETWEEN Sub1.MinId AND Sub1.MaxId
稍微快似乎和有一個簡單的解釋。
或者用空格以及NULLS
SELECT a.*
FROM geoname a
INNER JOIN
(
SELECT a.id AS MinId, IFNULL(MIN(b.id), MAX(c.id)) AS MaxId
FROM geoname a
LEFT OUTER JOIN geoname b
ON a.id < b.id AND b.name IS NOT NULL OR b.name = ''
CROSS JOIN geoname c
WHERE a.name = 'geo'
GROUP BY a.id
) Sub1
ON a.id BETWEEN Sub1.MinId AND Sub1.MaxId
應付爲什麼它應該包括這些記錄時,他們沒有'name =「緣」? – Barmar
你好,社區在這裏是嚴格的。你必須提出一個適當的問題。順便說一句。你只有一個名字爲'geo'的記錄,所以這個查詢會輸出'43435 re @ eae' –
這是什麼表中缺少名字?這是你的真實表格數據嗎?如果是這樣,查詢將只返回第4行。 –