简体   繁体   中英

SQL: Issue with WHERE Clause

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

The above query generates the error

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

If I remove the WHERE clause it works perfectly OK. I am not sure if there is an issue with the syntax?

WHERE condition needs to go after joins, try to move it to the end:

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

Well the Syntax is just wrong. You have to move the WHERE after your JOIN

For example:

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

If you tried to pre-filter your table Interests you can do that this way:

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;

Just a hint after all. I would suggest you, to use aliases for every table. It will improve the reading and will save you if you need to rename a table.

The where goes after the from clause. And join is part of the from clause.

Your query would be easier to write and to read with aliases:

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';

If you don't need the DISTINCT , then you should remove it. It only hurts performance.

In fact, a better way to write this query is to use a correlated subquery:

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';

This assumes that Vertical_Name is in Interests . Otherwise, it would go in the subquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM