SQL:WHERE子句的问题

时间:2015-06-21 13:09:19

标签: sql sql-server

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

以上查询生成错误

  

查找错误 - SQL Server数据库错误:关键字'内部'附近的语法不正确。

如果我删除了WHERE子句,它就完全正常了。我不确定语法是否存在问题?

3 个答案:

答案 0 :(得分:2)

//set var userData = { 'userId': $scope.userId, 'userName': $scope.userName }; shareDataService.setAppData('userData', userData); //get var sharedUserData = shareDataService.getAppData('userData'); $scope.userId = sharedUserData.userId; $scope.userName = sharedUserData.userName; 条件需要在连接之后进行,尝试将其移动到最后:

WHERE

答案 1 :(得分:1)

语法错误。您必须在WHERE

之后移动JOIN

例如:

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;

毕竟只是一个暗示。我建议你,为每张桌子使用别名。如果您需要重命名表格,它将改善阅读并节省您的费用。

答案 2 :(得分: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_Name位于Interests。否则,它将进入子查询。