当涉及JOIN时,如何最好地获得前2个唯一行?

时间:2009-07-16 07:06:24

标签: sql sql-server tsql

我有这个问题:

select top(2)
    property_id_ref
    ,image_file
    ,property_name 
from property_master a 
inner join image_master b 
    on a.property_id=b.property_id_ref 
inner join customer_master c 
    on a.customer_id=c.customer_id 

当我执行它时,我得到以下结果:

512 ~/propertyimg/3954493 id_1.jpg  Commercial Land 
512 ~/propertyimg/3954493.jpg   Commercial Land 

但是我需要property_id_ref中的image_file输出与property_id_ref不同,如下所示:

512 ~/propertyimg/3954493 id_1.jpg  Commercial Land 
513 ~/propertyimg/3119918 Id.jpg    Residential Plot 

为此我做了一个查询:

select top(2) 
    max(pm.property_name) as property_name
    ,max(im.property_id_ref) as property_id_ref
    ,CONVERT(varchar(5000),  max( CONVERT(binary, im.image_file))) as image_file 
from property_master pm
inner join image_master im
    on pm.property_id=im.property_id_ref 
inner join customer_master cm
    on pm.customer_id=cm.customer_id 
group by im.property_id_ref

所以我得到了与我预期的输出相同的输出。我想知道这是否是正确的方法,还是有其他更好的方法来做同样的事情?

我正在使用SQL Server 2005。

2 个答案:

答案 0 :(得分:1)

如果您真的只有您在示例中发布的查询,这将正常工作:

SELECT TOP (2)
    pm.property_id,
    pm.property_name,
    (SELECT TOP 1 image_file
     FROM image_master
     WHERE property_id_ref = pm.property_id) AS image_file
FROM
    property_master pm
-- This is only needed if it's possible that [image_file] can be NULL and you
-- don't want to get those rows.
WHERE
    EXISTS (SELECT * FROM image_master
            WHERE property_id_ref = pm.property_id)

我认为您的查询比这更复杂,但除非您发布真实的查询,否则我无法为您提供更具体的查询。

答案 1 :(得分:0)

你做的是正确的。 ID_Ref的分组和最大的随机成员。 它完全没问题,我认为没有理由改变它。