美好的一天。
查询从数据库中的表中选择不同的行:
SELECT
DISTINCT
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,
p.name as p_name
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
导航我使用NOT IN:
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,
p.name as p_name
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
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 p.id_city='73041' AND p.include='1' AND p.blocked='0' AND f.blocked='0' AND p.id_group='44' AND p.id_subgroup='266'
ORDER BY f.name ASC
)
AND p.id_firm=f.id_firm AND p.id_city='73041' AND p.include='1' AND p.blocked='0'
AND f.blocked='0' AND p.id_group='44' AND p.id_subgroup='266'
ORDER BY f.name ASC
在上一次查询中检查f.name NOT IN
,但我需要检查第一个查询中的整个字符串,而不仅仅是f.name
。
怎么做到这个?
答案 0 :(得分:2)
这可能对你有所帮助 -
;WITH cte AS
(
SELECT DISTINCT
f_id_service = f.id_service
, f_id_city = f.id_city
, f_name = f.name
, f_address = f.[address]
, f_business = f.business
, f_web = f.web
, f_phone = f.phone
, f_id_firm = f.id_firm
, p_name = p.name
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 p.id_city = '73041'
AND p.[include] = '1'
AND p.blocked = '0'
AND f.blocked = '0'
AND p.id_group = '44'
AND p.id_subgroup = '266'
)
SELECT TOP 20
f_id_service
, f_id_city
, f_name
, f_address
, f_business
, f_web
, f_phone
, f_id_firm
, p_name
FROM cte
WHERE f_name NOT IN (
SELECT DISTINCT TOP 20 f_name
FROM cte
ORDER BY f_name
)
ORDER BY f_name
答案 1 :(得分:2)
SELECT f.name as f_name,
max(f.address) as f_address,
max(f.business) as f_business,
max(f.web) as f_web,
max(f.phone) as f_phone,
max(p.name) as p_name
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 TOP $numnext
f.name
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
p.id_firm=f.id_firm AND p.id_city='73041' AND p.include='1' AND p.blocked='0'
AND f.blocked='0' AND p.id_group='44' AND p.id_subgroup='266'
GROUP BY f.name
ORDER BY f.name ASC
)
AND
p.id_firm=f.id_firm AND p.id_city='73041' AND p.include='1' AND p.blocked='0'
AND f.blocked='0' AND p.id_group='44' AND p.id_subgroup='266'
GROUP BY f.name
ORDER BY f.name ASC