0

我有疑问:

SELECT TOP 20 f.id_service AS f_id_service,
              f.id_city    AS f_id_city,
              f.name       AS f_name,
              f.address    AS f_address,
              f.business   AS f_business,
              f.web        AS f_web,
              f.phone      AS f_phone,
              f.id_firm    AS f_id_firm
FROM   Firm f
       LEFT JOIN Price p
         ON p.id_service = f.id_service
            AND p.id_city = f.id_city
            AND p.id_firm = f.id_firm
WHERE  f.name NOT IN (SELECT DISTINCT TOP 20 f.name
                      FROM   Firm f
                      WHERE  f.blocked = '0'
                             AND ( f.name LIKE 'АВТО%'
                                    OR f.phone LIKE 'АВТО%' )
                             AND ( f.phone != ''
                                    OR f.address != '' )
                             AND f.id_city = '73041'
                      ORDER  BY f.name ASC)
       AND f.dogovor = '1'
       AND f.blocked = '0'
       AND ( f.name LIKE 'АВТО%'
              OR f.phone LIKE 'АВТО%' )
       AND ( f.phone != ''
              OR f.address != '' )
       AND f.id_city = '73041

请告诉我如何使这个查询只选择唯一的 f.name ?

4

3 回答 3

4

将 SELECT 更改为此

SELECT DISTINCT TOP 20 
    f.name as f_name
FROM ...

您不能拥有所有列值,但 DISTINCT 只是其中之一:这没有任何意义。

于 2013-05-21T15:32:36.020 回答
3

尝试这个

SELECT DISTINCT
TOP 20 
f.id_service as f_id_service, 
f.id_city as f_id_city, 
f.name as f_name, 
f.address as f_address, 
f.business as f_business, 
f.web as f_web, 
于 2013-05-21T15:35:21.817 回答
1

使用DISTINCT关键字:

SELECT DISTINCT
TOP 20 
f.id_service as f_id_service, 
f.id_city as f_id_city, 
f.name as f_name, 
f.address as f_address, 
f.business as f_business, 
f.web as f_web, 
f.phone as f_phone, 
f.id_firm as f_id_firm FROM Firm f 
left join Price p on p.id_service=f.id_service 
AND p.id_city=f.id_city AND p.id_firm=f.id_firm 
WHERE 
f.name NOT IN (
SELECT DISTINCT TOP 20 f.name FROM Firm f 
WHERE f.blocked='0' 
AND (f.name LIKE 'АВТО%' OR f.phone LIKE 'АВТО%') 
AND (f.phone !='' OR f.address != '') AND f.id_city='73041' 
ORDER BY f.name ASC ) AND f.dogovor='1' 
AND f.blocked='0' AND (f.name LIKE 'АВТО%' OR f.phone LIKE 'АВТО%') 
AND (f.phone !='' OR f.address != '') 
AND f.id_city='73041'

因为你所有的列都来自一个表,除非name在表中是唯一的,否则firm你不能像这样使用 DISTINCT。您需要决定在重复的情况下显示哪个公司,然后制定一个复杂的查询来实现这一点。

于 2013-05-21T15:33:03.093 回答