2012-02-08 52 views
0

使用一個表在MySQL中,我如何在子查詢中創建JOIN?

工作樣品
SELECT t.* FROM (
    SELECT 
    TITLE.name, 
    (TITLE.value-TITLE.msp) AS Lower, 
    (TITLE.value+TITLE.msp) AS Upper, 
    (TITLE.value) AS Value 
    FROM TITLE 
) t 
WHERE 98 BETWEEN t.Lower AND t.Upper 
ORDER BY ABS(98 - t.Value) ASC 
LIMIT 5 

期望例如具有3個表(需要固定/幫助)

SELECT t.* FROM (
    SELECT 
    TITLE.name, ALBUM.year, GENRE.Type 
    (TITLE.value-TITLE.msp) AS Lower, 
    (TITLE.value+TITLE.msp) AS Upper, 
    (TITLE.value) AS Value 
    FROM TITLE, ALBUM, GENRE 
) t 
WHERE ALBUM.ID=GENRE.ID AND TITLE.ID=ALBUM.ID 
AND 98 BETWEEN t.Lower AND t.Upper 
ORDER BY ABS(98 - t.Value) ASC; 

我得到以下錯誤工作:

ERROR 1054 (42S22): Unknown column 'ALBUM.ID' in 'where clause'

+1

您的子查詢(「t」)正在返回排除其各自ID值的TITLE,ALBUM和GENRE的交叉結果集。你的WHERE子句只能在't'的投影上操作。 – 2012-02-08 18:29:24

回答

3

這是合乎邏輯的:你的子查詢創建一個表t,和後記嘗試引用表ALBUM。沒有ALBUM,只有t

最快的修復方法是移動它所屬的JOIN的WHERE子句:在子查詢中。

SELECT t.* FROM (
    SELECT 
    TITLE.name, ALBUM.year, GENRE.Type 
    (TITLE.value-TITLE.msp) AS Lower, 
    (TITLE.value+TITLE.msp) AS Upper, 
    (TITLE.value) AS Value 
    FROM TITLE, ALBUM, GENRE 
    WHERE ALBUM.ID=GENRE.ID AND TITLE.ID=ALBUM.ID 
) t 
WHERE 98 BETWEEN t.Lower AND t.Upper 
ORDER BY ABS(98 - t.Value) ASC; 

查詢本身是不是漂亮,但...爲什麼不試試這個:

SELECT 
    TITLE.name, ALBUM.year, GENRE.Type 
    (TITLE.value-TITLE.msp) AS Lower, 
    (TITLE.value+TITLE.msp) AS Upper, 
    (TITLE.value) AS Value 
    FROM TITLE 
    JOIN ALBUM 
    ON TITLE.ID=ALBUM.ID 
    JOIN GENRE 
    ON ALBUM.ID=GENRE.ID 
    WHERE 98 BETWEEN Lower AND Upper 
    ORDER BY ABS(98 - Value) ASC; 
  • 刪除了不必要的子查詢
  • 使用SQL-92式聯接,而不是SQL -89樣式JOIN(帶有where子句的笛卡爾積)
+0

有道理感謝Konerak&rsenna – stackoverflow 2012-02-08 19:02:32

+0

@Jammin我只是修正了他的「笛卡兒」的拼寫:) Konerak是唯一負責這個答案(我同意是最好的)。 – rsenna 2012-02-09 16:01:16

2

看看你的查詢:你正在定義一個名爲的子查詢,它在表TITLE,ALBUMGENRE之間做cartesian productThen您從該子查詢中選擇,並嘗試應用TITLE,ALBUMGENRE上的WHERE子句......但這些表已不在範圍內!

試試這個:

SELECT t.* FROM (
    SELECT 
    TITLE.name, ALBUM.year, GENRE.Type 
    (TITLE.value-TITLE.msp) AS Lower, 
    (TITLE.value+TITLE.msp) AS Upper, 
    (TITLE.value) AS Value 
    FROM TITLE, ALBUM, GENRE 
    WHERE ALBUM.ID=GENRE.ID AND TITLE.ID=ALBUM.ID 
) t 
WHERE 98 BETWEEN t.Lower AND t.Upper 
ORDER BY ABS(98 - t.Value) ASC; 
1

將WHERE子句移到內部查詢中。

SELECT t.* FROM (
    SELECT 
    TITLE.name, ALBUM.year, GENRE.Type 
    (TITLE.value-TITLE.msp) AS Lower, 
    (TITLE.value+TITLE.msp) AS Upper, 
    (TITLE.value) AS Value 
    FROM TITLE, ALBUM, GENRE 
    WHERE ALBUM.ID=GENRE.ID AND TITLE.ID=ALBUM.ID 
) t 
AND 98 BETWEEN t.Lower AND t.Upper 
ORDER BY ABS(98 - t.Value) ASC;