2011-09-16 26 views
0

我与我的数据库有多对多的关系,所以我创建了一个sql查询,稍后我将用于搜索。 现在我想要做的是从我的搜索结果(独特的公司名称)中获取唯一的值。获取唯一值作为查询结果

这是我的查询:

SELECT agencies.company 
    ,agencies.website_url 
    ,agencies.STATUS 
    ,agencies.size 
    ,IndustryData.industry_id 
    ,ProfessionData.profession_id 
    ,SectorData.sector_id 
    ,seniorityData.seniority_id 
    ,ZonesData.zone_id 
FROM agencies 
LEFT JOIN (
    SELECT agencies_industries.agency_id 
     ,agencies_industries.industry_id 
    FROM agencies_industries 
    ) AS IndustryData ON agencies.id = IndustryData.agency_id 
LEFT JOIN (
    SELECT agencies_professions.agency_id 
     ,agencies_professions.profession_id 
    FROM agencies_professions 
    ) AS ProfessionData ON agencies.id = ProfessionData.agency_id 
LEFT JOIN (
    SELECT agencies_sectors.agency_id 
     ,agencies_sectors.sector_id 
    FROM agencies_sectors 
    ) AS SectorData ON agencies.id = SectorData.agency_id 
LEFT JOIN (
    SELECT agencies_seniorities.agency_id 
     ,agencies_seniorities.seniority_id 
    FROM agencies_seniorities 
    ) AS SeniorityData ON agencies.id = SeniorityData.agency_id 
LEFT JOIN (
    SELECT agencies_zones.agency_id 
     ,agencies_zones.zone_id 
    FROM agencies_zones 
    ) AS ZonesData ON agencies.id = ZonesData.agency_id 
WHERE IndustryData.industry_id = 3 
    AND ProfessionData.profession_id = 1 

结果看起来是这样的:

公司,WEBSITE_URL,状态,大小,industry_id,profession_id,sector_id,seniority_id,zone_id

  1. Nine nine.com 1 3 3 1 3 2 1
  2. Nine nine.com 1 3 3 1 3 2 5
  3. 九nine.com 1 3 3 1 3 2 8
  4. 九nine.com 1 3 3 1 3 5 1
  5. 九nine.com 1 3 3 1 3 5 5
  6. 九nine.com 1 3 3 1 3 5 8
  7. 十ten.com 2 3 3 1 3 1 1
  8. 十ten.com 2 3 3 1 3 1 3
  9. 十ten.com 2 3 3 1 3 1 7
  10. Ten ten.com 2 3 3 1 3 3 1
  11. Ten ten.com 2 3 3 1 3 3 3
  12. 十ten.com 2 3 3 1 3 3 7
  13. 十ten.com 2 3 3 1 3 5 1
  14. 十ten.com 2 3 3 1 3 5 3
  15. 十ten.com 2 3 3 1 3 5 7

我想摆脱公司名称的重复。我怎么做?

+1

有很多方法 - 你想做的事与改变最后两个值,但什么? – RedFilter

+0

你只需要公司名称或更多? – Matschie

+0

@RedFilter这只是一个例子,不用担心这两个值有所不同 - 稍后我将使用此代码来创建搜索 –

回答

0

你可以使用一个GROUP BY为此,例如:

SELECT agencies.company 
    ,agencies.website_url 
    ,agencies.STATUS 
    ,agencies.size 
    ,IndustryData.industry_id 
    ,ProfessionData.profession_id 
    ,SectorData.sector_id 
FROM ... 
GROUP BY agencies.company 
    ,agencies.website_url 
    ,agencies.STATUS 
    ,agencies.size 
    ,IndustryData.industry_id 
    ,ProfessionData.profession_id 
    ,SectorData.sector_id 
+0

谢谢,这是我所需要的。 –