2011-08-02 61 views
1

任何人都可以幫助我,我有點卡住了。SQL查詢錯誤:Where子句中'不知道columnName'

我有這個疑問這就像一個魅力

SELECT * , 
     matches - falsepositives AS hits 
FROM (
    SELECT c. * , 
      IFNULL(p.total, 0) AS matches, 
      (
       SELECT COUNT(*) 
       FROM ci_falsepositives n 
       WHERE n.addressbook_id = c.reference 
       AND n.sanction_key 
       IN (
        SELECT sanction_key 
        FROM ci_matched_sanctions 
       ) 
      ) AS falsepositives 
    FROM ci_address_book c 
    LEFT JOIN (
     SELECT addressbook_id, 
       COUNT(match_id) AS total 
     FROM ci_matched_sanctions 
     GROUP BY addressbook_id 
    ) AS p 
     ON c.id = p.addressbook_id 
) AS S 
WHERE matches > 0 
ORDER BY hits DESC 

但我想改變它進行排序,其中點擊率是大於0,但它告訴我,它不知道命中...是它是因爲它是2項的計算?

回答

3

您不能在WHERE子句中使用別名列。你需要重寫一遍:

SELECT * , 
     matches - falsepositives AS hits 
FROM (
    SELECT c. * , 
      IFNULL(p.total, 0) AS matches, 
      (
       SELECT COUNT(*) 
       FROM ci_falsepositives n 
       WHERE n.addressbook_id = c.reference 
       AND n.sanction_key 
       IN (
        SELECT sanction_key 
        FROM ci_matched_sanctions 
       ) 
      ) AS falsepositives 
    FROM ci_address_book c 
    LEFT JOIN (
     SELECT addressbook_id, 
       COUNT(match_id) AS total 
     FROM ci_matched_sanctions 
     GROUP BY addressbook_id 
    ) AS p 
     ON c.id = p.addressbook_id 
) AS S 
WHERE matches - falsepositives > 0 
ORDER BY hits DESC 

或者使用子查詢:

SELECT * FROM (
    SELECT * , 
      matches - falsepositives AS hits 
    FROM (
     SELECT c. * , 
       IFNULL(p.total, 0) AS matches, 
       (
        SELECT COUNT(*) 
        FROM ci_falsepositives n 
        WHERE n.addressbook_id = c.reference 
        AND n.sanction_key 
        IN (
         SELECT sanction_key 
         FROM ci_matched_sanctions 
        ) 
       ) AS falsepositives 
     FROM ci_address_book c 
     LEFT JOIN (
      SELECT addressbook_id, 
        COUNT(match_id) AS total 
      FROM ci_matched_sanctions 
      GROUP BY addressbook_id 
     ) AS p 
      ON c.id = p.addressbook_id 
    ) AS S 
) AS S2 
WHERE hits > 0 
ORDER BY hits DESC 
+0

謝謝你,工作就像一個魅力!我會記住這一點,我認爲我可以在其上創建一個where子句... – renevdkooi