2015-06-21 127 views
-2
SELECT DISTINCT Interests.Interest_name, Impressions.Count 
FROM Interests 
WHERE Vertical_name = 'Retail' 
INNER JOIN Impressions ON Interests.Interest_Name = Impressions.Interest_Name; 

上述查詢生成錯誤SQL:問題與WHERE子句

Lookup Error - SQL Server Database Error: Incorrect syntax near the keyword 'Inner'.

如果我刪除WHERE條款它的工作原理完全確定。我不確定是否存在語法問題?

+2

where子句應該在連接之後出現。投票結束爲簡單的語法錯誤。 – jpw

回答

2

WHERE條件需要去後加入,嘗試將其移動到結束:

SELECT DISTINCT Interests.Interest_name,Impressions.Count FROM Interests 
Inner Join Impressions ON Interests.Interest_Name = Impressions.Interest_Name 
WHERE Vertical_name = 'Retail'; 
1

嘛語法是錯誤的。你有你的JOIN

後移動WHERE例如:

SELECT DISTINCT Interests.Interest_name,Impressions.Count 
FROM Interests 
INNER JOIN Impressions 
    ON Interests.Interest_Name = Impressions.Interest_Name 
WHERE Vertical_name = 'Retail'; 

如果你想預篩選表Interests你能做到這一點是這樣的:

SELECT DISTINCT Interests.Interest_name,Impressions.Count 
FROM (
    SELECT * 
    FROM Interests 
    WHERE Vertical_name = 'Retail' 
    ) as Interests 
INNER JOIN Impressions 
    ON Interests.Interest_Name = Impressions.Interest_Name; 

只是一個提示畢竟。我建議你,爲每個表使用別名。如果您需要重命名錶格,它將改善閱讀並節省您的時間。

1

where條款from條款。 joinfrom子句的一部分。

您的查詢會更容易編寫,並用別名閱讀:

SELECT DISTINCT i.Interest_name, i.Count 
FROM Interests i Inner Join 
    Impressions im 
    ON i.Interest_Name = im.Interest_Name; 
WHERE Vertical_name = 'Retail'; 

如果您不需要DISTINCT,那麼你應該將其刪除。它只會傷害表現。

事實上,一個更好的方式來寫這個查詢是使用相關子查詢:

SELECT DISTINCT i.Interest_name, i.Count 
FROM Interests i 
WHERE EXISTS (SELECT 1 
       FROM Impressions im 
       WHERE i.Interest_Name = im.Interest_Name 
      ) 
WHERE i.Vertical_name = 'Retail'; 

這假定Vertical_NameInterests。否則,它會進入子查詢。