2014-01-29 154 views
0

我有一個具有不同形式版本的窗體集合的數據庫。下面的「正在工作」查詢通過每個表格版本的批准使用日期成功選擇最新的表格版本。MySQL問題:內部加入子查詢返回沒有結果

我想加入這個查詢「工作」查詢與另一個名爲「forms_types」的表,返回列「form_type」的全文描述。

我嘗試這樣做是行不通的 - 我應該在查詢的「加入」版本上獲得50個結果,但它不會返回任何結果。

任何幫助或見解將不勝感激讓我的工作查詢加入正確!

工作(50個結果,但沒有JOIN):

SELECT * 
FROM forms AS t 
WHERE california = 
    ( 
    SELECT MAX(california) 
    FROM forms 
    WHERE `form_number` = t.`form_number` 
    AND trucking_coverage= 1 
    AND california IS NOT NULL 
    AND california <= '2014-01-29' 
    AND form_type <> 0 
    ) 
ORDER BY `t`.`form_type` ASC, `t`.`form_number` ASC 

無法正常工作(無結果):

SELECT * 
FROM forms AS t 
INNER JOIN forms_types 
ON 'forms.form_type' = 'forms_types.form_type' 
WHERE california = 
    ( 
    SELECT MAX(california) 
    FROM forms 
    WHERE `form_number` = t.`form_number` 
    AND trucking_coverage= 1 
    AND california IS NOT NULL 
    AND california <= '2014-01-29' 
    AND form_type <> 0 
    ) 
ORDER BY `t`.`form_type` ASC, `t`.`form_number` ASC 
+0

您可以顯示'forms'表一表模式? – peterm

回答

1

您正在尋找這樣的事情?

SELECT f.*, t.* 
    FROM 
( 
    SELECT form_number, MAX(california) california 
    FROM forms 
    WHERE trucking_coverage = 1 
    AND california IS NOT NULL 
    AND california <= '2014-01-29' 
    AND form_type <> 0 
    GROUP BY form_number 
) q JOIN forms f 
    ON q.form_number = f.form_number 
    AND q.california = f.california JOIN forms_types t 
    ON f.form_type = t.form_type 
ORDER BY f.form_type, f.form_number 

它也可以寫成這樣(通過利用非標準的MySQL GROUP BY擴展)

SELECT * 
    FROM 
(
    SELECT * 
    FROM forms f JOIN forms_types t 
     ON f.form_type = t.form_type 
    WHERE f.trucking_coverage = 1 
    AND f.california IS NOT NULL 
    AND f.california <= '2014-01-29' 
    AND f.form_type <> 0 
    ORDER BY california DESC 
) q 
GROUP BY f.form_number 
ORDER BY f.form_type, f.form_number 
+0

謝謝!完美地工作! – dabra904

+0

你很受歡迎。祝你好運 :) – peterm