我知道下面的查询非常糟糕,需要2分钟才能获得10条记录(虽然列表中有超过1M的记录)但是我不确定最好的方法是写这个
我只是想让所有列出表格的国家/地区连接到国家/地区的列表是省..
ALTER VIEW [dbo].[CountriesWithListings]
AS
SELECT distinct
cn.CountryID,
cn.Code as CountryCode,
cn.Name as CountryName
FROM dbo.Countries AS cn
INNER JOIN dbo.Provinces AS p ON p.CountryID = cn.CountryID
INNER JOIN dbo.Cities c on c.ProvinceID = p.ProvinceID
INNER JOIN dbo.Listings AS l ON l.CityID = c.CityID
WHERE l.IsActive = 1 AND l.IsApproved = 1
答案 0 :(得分:2)
假设您有适当的索引,使用distinct
是很昂贵的。您应该可以使用exists
:
SELECT
cn.CountryID,
cn.Code as CountryCode,
cn.Name as CountryName
FROM dbo.Countries AS cn
WHERE EXISTS (
SELECT 1
FROM dbo.Provinces AS p
INNER JOIN dbo.Cities c on c.ProvinceID = p.ProvinceID
INNER JOIN dbo.Listings AS l ON l.CityID = c.CityID
WHERE p.CountryID = cn.CountryID
AND l.IsActive = 1
AND l.IsApproved = 1
)
答案 1 :(得分:0)
列表是否已编入索引?如果它有1M个条目,那么最好先将其编入索引并在此之后检查性能。您的查询并不复杂
答案 2 :(得分:0)
查询的性能还取决于您环境中存在的索引以及您正在使用的列。
试试这个......
SELECT cn.CountryID
,MIN(cn.Code) AS CountryCode
,MIN(cn.NAME) AS CountryName
FROM dbo.Countries AS cn
INNER JOIN dbo.Provinces AS p ON p.CountryID = cn.CountryID
INNER JOIN dbo.Cities c ON c.ProvinceID = p.ProvinceID
INNER JOIN dbo.Listings AS l ON l.CityID = c.CityID
WHERE l.IsActive = 1
AND l.IsApproved = 1
GROUP BY cn.CountryID
答案 3 :(得分:0)
如果不添加索引或其他性能调优,此查询应该运行得更快:
ALTER VIEW [dbo].[CountriesWithListings]
AS
SELECT cn.CountryID, cn.Code as CountryCode, cn.Name as CountryName
FROM dbo.Countries AS cn
WHERE cn.CountryID IN
(
SELECT p.CountryId FROM dbo.Provinces
INNER JOIN dbo.Cities c on c.ProvinceID = p.ProvinceID
INNER JOIN dbo.Listings AS l ON l.CityID = c.CityID
WHERE l.IsActive = 1 AND l.IsApproved = 1
)