2014-02-11 68 views
0

我不斷收到在PHP以下錯誤:「您的SQL語法錯誤;檢查對應於您的MySQL服務器版本正確的語法附近SQL語法錯誤在PHP

'IN (SELECT invoiceNo FROM sales2012 GROUP BY invoiceNo HAVING COUNT(invoiceNo)>1' 
at line 1 
使用手冊

我的查詢如下:

$query = "SELECT invoiceNo, invoiceDate, dueDate, customerID, customerName, 
dateTrans, postDate, description, grossSale, vat, netSale, quantity, 
branch, despatchNote 
FROM 
sales2012 WHERE invoiceNo IN (
    SELECT invoiceNo FROM sales2012 GROUP BY invoiceNo HAVING COUNT(invoiceNo)>1)"; 

當我運行像SELECT *一個簡單的查詢FROM sales2012我得到完美的結果,甚至當我運行查詢,直到IN子句運行以及由於某種原因。當我運行整個事情時它崩潰。

我也使用SQL Workbench運行相同的代碼,並打印出我正在查找的表格。我知道代碼的作品,我只是不明白爲什麼它不能在PHP中工作。

我也改變了執行時間,但也沒有工作。

任何幫助將不勝感激。 感謝

+0

你究竟在做什麼? – Strawberry

+0

我試圖在sales2012中打印所有重複項。我應該得到4作爲輸出。如果我使用沒有IN子句的語法,它將打印2行而不是4,並使用IN子句打印錯誤 – goroved

+0

考慮提供正確的DDL(和/或sqlfiddle)與期望的結果集 – Strawberry

回答

2

正確的查詢是:

$query = "SELECT invoiceNo, invoiceDate, dueDate, customerID, customerName, dateTrans, postDate, description, grossSale, vat, netSale, quantity, branch, despatchNote 
      FROM sales2012 
      WHERE invoiceNo IN (SELECT invoiceNo FROM sales2012 GROUP BY invoiceNo HAVING COUNT(invoiceNo)>1)"; 

但更好的查詢是:

$query = "SELECT invoiceNo, invoiceDate, dueDate, customerID, customerName, dateTrans, postDate, description, grossSale, vat, netSale, quantity, branch, despatchNote 
      FROM sales2012 s1 
      INNER JOIN (SELECT invoiceNo FROM sales2012 GROUP BY invoiceNo HAVING COUNT(invoiceNo)>1) 
      as s2 on s2.invoiceNo = s1.invoiceNO"; 
+0

嗨,感謝您的回覆。我確實在原始語法中有WHERE invoiceNo。我輸入了更好的查詢,現在它告訴我「欄位列表中的列'invoiceNo'不明確」。你知道這意味着什麼嗎? – goroved

+0

使用表sales2012中的別名,然後在select語句中使用此別名。例如:SELECT sales.invoiceNo,invoiceDate,dueDate,customerID,customerName,dateTrans,postDate,description,grossSale,vat,netSale,quantity,branch,despatchNote FROM sales2012 sales WHERE sales.invoiceNo IN(SELECT invoiceNo FROM sales2012 GROUP BY invoiceNo HAVING COUNT(invoiceNo)> 1)「; – Ganz

+0

IT WORKED !!!!非常感謝你!!!我花了2天的時間想辦法解決這個問題!! – goroved

2

如果你看看這個:

FROM sales2012 IN (SELECT invoiceNo 

你會看到的東西是失蹤。它應該類似於

FROM sales2012 
where somefield IN (SELECT invoiceNo 
+0

對不起,我確實做了有WHERE invoiceNo IN(SELECT),但由於某種原因,它不想爲我工作 – goroved