获取唯一值作为查询结果

时间:2011-09-16 13:56:18

标签: mysql

我与我的数据库有多对多的关系,所以我创建了一个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,status,size,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 nine.com 1 3 3 1 3 2 8
  4. Nine nine.com 1 3 3 1 3 5 1
  5. Nine nine.com 1 3 3 1 3 5 5
  6. Nine nine.com 1 3 3 1 3 5 8
  7. Ten ten.com 2 3 3 1 3 1 1
  8. Ten ten.com 2 3 3 1 3 1 3
  9. Ten 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 ten.com 2 3 3 1 3 3 7
  13. Ten ten.com 2 3 3 1 3 5 1
  14. Ten ten.com 2 3 3 1 3 5 3
  15. Ten ten.com 2 3 3 1 3 5 7
  16. 我想摆脱公司名称的重复。我该怎么做?

2 个答案:

答案 0 :(得分:0)

也许您可以使用变量和子查询来做到这一点,如下所示:

http://dev.mysql.com/doc/refman/5.0/en/user-variables.html

但也许在您的代码中执行此操作比在查询中更快。

答案 1 :(得分: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