SQL将列表与列表进行比较

时间:2015-10-16 09:37:31

标签: sql left-join

我有3张桌子:tbl_companytbl_locationtbl_category。 每家公司都可以拥有多个地点和多个类别。

因此表格的字段如下:

tbl_companyco_idtitle

tbl_location_memberloc_idco_id

tbl_category_membercat_idco_id

因此,我的参数是类别ID和位置ID列表,结果应显示符合条件的公司。

我的查询如下:

SELECT  
      cc.co_id
      ,cc.title
      ,cc.subtitle

FROM tbl_company AS cc
LEFT JOIN tbl_category_member as cm ON cm.co_id = cc.co_id 
LEFT JOIN tbl_location_member as lm ON lm.co_id = cc.co_id 
WHERE publish=1
AND cm.cat_id  IN (14,16)
AND lm.loc_id IN (1,2)

此查询的问题在于它返回公司4次。 原因是该公司符合所有4个标准。 有没有其他方法可以实现这个目标?

4 个答案:

答案 0 :(得分:0)

应该是评论,但我需要更多空间......

SELECT  
      cc.co_id
      ,cc.title
      ,cc.subtitle
FROM tbl_company AS cc
LEFT JOIN tbl_category_member as cm ON cm.co_id = cc.co_id
                                   AND cm.cat_id  IN (14,16)
LEFT JOIN tbl_location_member as lm ON lm.co_id = cc.co_id
                                   AND lm.loc_id IN (1,2)
WHERE publish=1

答案 1 :(得分:0)

只需添加public class SomeService { private readonly IARepository _aRepository; private readonly IBRepository _bRepository; public EventService(IARepository aRepository, IBRepository bRepository) { _aRepository = aRepository; _bRepository = bRepository; } public EventService() : this(new ARepository(), new BRepository()) { } public IEnumerable<SomeDTO> GetSomeDTOs() { return _aRepository.GetAll() .Join(_bRepository.GetAll(), a => a.SomeId, b => b.SomeId, (c, d) => new SomeDTO { ... ... ... }).ToList(); } }

DISTINCT

答案 2 :(得分:0)

因为你想选择公司我做一个这样的子查询:

SELECT  
      cc.co_id
      ,cc.title
      ,cc.subtitle

FROM tbl_company AS cc
WHERE  publish=1
AND (
cc.co_id in (select cm.co_id from  tbl_category_member cm where cm.cat_id  IN (14,16))
or  cc.co_id in (select lm.co_id from  tbl_location_member lm where lm.loc_id IN (1,2))
)

答案 3 :(得分:0)

将DISTINCT添加到SELECT:

SELECT DISTINCT 
  cc.co_id
  ,cc.title
  ,cc.subtitle

FROM tbl_company AS cc
LEFT JOIN tbl_category_member as cm ON cm.co_id = cc.co_id 
LEFT JOIN tbl_location_member as lm ON lm.co_id = cc.co_id 
WHERE publish=1
AND cm.cat_id  IN (14,16)
AND lm.loc_id IN (1,2)

你也可以对GROUP BY cc.co_id做同样的事情,但是我最近发现,不是所有的SQL语言(看着你的MSSQL)