2011-09-16 27 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

謝謝,這是我所需要的。 –