Mysql group_concat与distinct和where给出了奇怪的结果

时间:2014-05-22 09:56:57

标签: php mysql group-concat find-in-set

我有以下查询可以正常工作(见下文)。

但是当我添加条件时,例如AND (specialtyName = '...'),主要结果很好,但GROUP_CONCAT只显示与条件匹配的结果。

有人可以帮我解决这个问题吗?

提前致谢。

佛瑞德。

SELECT 

    tblJobs.jobID, 
    tblJobs.jobName, 
    DATE_FORMAT(tblJobs.jobDate,'%d-%m-%Y'), 

    tblCompanies.companyID, 
    tblCompanies.companyName, 
    tblCompanies.companyNameConvert, 

    GROUP_CONCAT(DISTINCT tblSpecialties.specialtyName 
        ORDER BY FIELD (
            specialtyName, 
            'specialtyName1', 
            'specialtyName2', 
            'specialtyName3'), 
            specialtyName ASC) 
        AS specialtyNames, 

    GROUP_CONCAT(DISTINCT tblSpecialties.specialtyNameConvert 
        ORDER BY FIELD (
            specialtyName, 
            'specialtyName1', 
            'specialtyName2', 
            'specialtyName3'), 
            specialtyName ASC) 
        AS specialtyNamesConvert, 

    GROUP_CONCAT(DISTINCT tblRegions.regionName), 
    GROUP_CONCAT(DISTINCT tblRegions.regionNameConvert) 

FROM tblJobs 

LEFT JOIN tblCompanies ON 
(tblJobs.jobCompany = tblCompanies.companyID) 

LEFT JOIN tblSpecialties ON 
FIND_IN_SET(tblSpecialties.specialtyID, REPLACE(tblJobs.jobSpecialty,' ',',')) 

LEFT JOIN tblRegions ON 
FIND_IN_SET(tblRegions.regionID, REPLACE(tblJobs.jobRegion,' ',','))

WHERE 

    AND jobActive = '1' 
    AND jobDate >= '2013-01-01' 
    AND companyActive = '1' 

GROUP BY jobID 
ORDER BY jobDate DESC, jobID DESC, jobCompany DESC

2 个答案:

答案 0 :(得分:0)

我认为为表和子查询使用别名可以解决您的问题。 你可以尝试这样的事情:

SELECT 

tblJobs.jobID, 
tblJobs.jobName, 
DATE_FORMAT(tblJobs.jobDate,'%d-%m-%Y'), 

tblCompanies.companyID, 
tblCompanies.companyName, 
tblCompanies.companyNameConvert,  
(SELECT GROUP_CONCAT(DISTINCT ts.specialtyName 
        ORDER BY FIELD (
            specialtyName, 
            'specialtyName1', 
            'specialtyName2', 
            'specialtyName3'), 
            specialtyName ASC) 
        FROM tblSpecialties ts) AS specialtyNames , 
, ... ,
FROM tblJobs 

LEFT JOIN tblCompanies ON 
(tblJobs.jobCompany = tblCompanies.companyID) 

LEFT JOIN tblSpecialties ON 
FIND_IN_SET(tblSpecialties.specialtyID, REPLACE(tblJobs.jobSpecialty,' ',',')) 

LEFT JOIN tblRegions ON 
FIND_IN_SET(tblRegions.regionID, REPLACE(tblJobs.jobRegion,' ',','))

WHERE 

    AND jobActive = '1' 
    AND jobDate >= '2013-01-01' 
    AND companyActive = '1' 

GROUP BY jobID 
ORDER BY jobDate DESC, jobID DESC, jobCompany DESC

我没有测试过这段代码,但它可以提供帮助。

答案 1 :(得分:0)

如果你说:

WHERE jobActive = '1' AND jobDate >= '2013-01-01' AND companyActive = '1' AND
      specialties = XXX

那么你只会得到那些专业。过滤在聚合之前完成。注意:在where子句中包含这样的条件也会将外连接转换为内连接。您的联接可能是正确对齐的外键关系,因此内部联接可能是合适的。

我猜你真正想要的是过滤具有这种专业的人的工作,但要保留所有其他信息。您希望在聚合后进行过滤。使用having子句而不是where子句执行此操作:

having sum(specialties = XXX) > 0;

这将仅保留具有特定专长的行,并保留所有其他信息。