MySQL:通过" group by"将功能搜索到聚合列中。

时间:2015-01-29 21:01:08

标签: php mysql group-by

我有3张桌子:成员,照片和标记。会员可以张贴图片并对其他会员的图片进行排名。

我正在用PHP编写一个脚本,它返回一张照片(使用random()),该照片可以由在其成员区域中连接的用户进行排名。因此,我做了以下查询(我评论显然包含问题的行):

 SELECT ph.*, 
    COUNT(note) 'nb_note', 
    ROUND(DEGREES(ACOS((SIN(RADIANS( 48.86 )) * SIN (RADIANS( v.latitude_deg ))) + (COS(RADIANS( 48.86 )) * COS(RADIANS( v.latitude_deg )) * COS( RADIANS( 2.34445 - v.longitude_deg))))) * 111.13384) 'distance', 

    ((UNIX_TIMESTAMP() - UNIX_TIMESTAMP(mb.anniv)) / 3600 / 24 / 365) AS 'age' , mb.sexe, pr.orientation, mb.pseudo, mb.anniv,mb.ID 'ID_membre' 

    FROM photos__ ph 

    LEFT JOIN photos__rank rk ON rk.ID_photo = ph.ID 
    LEFT JOIN photos__signalements sg ON sg.ID_photo = ph.ID 
    INNER JOIN membre__ mb ON mb.ID = ph.ID_membre 
    INNER JOIN membre__profil pr ON pr.ID_membre = mb.ID 
    INNER JOIN site__villes v ON v.ID = pr.ID_ville 

    // '96' is the currently connected member, written into the query by PHP
    WHERE mb.ID <> '96'
// THE FOLLOWING LINE SHOULD PREVENT THE QUERY TO RETURN PICTURES ALREADY RANKED // BY THE USER CURRENTLY CONNECTED, BUT IT DOESN'T WORK :
    AND (rk.ID_membre <> '96' OR ISNULL(note)) // THIS LINE DOESN'T WORK
// SAME PROBLEMS WITH PICTURES ALREADY REPORTED BY THE USER '96' (the connected):    
 AND (sg.ID_membre <> '96' OR ISNULL(sg.ID)) // AND THIS ONE AS WELL
    AND ph.innotable = 0 
    AND mb.sexe = 'f' 
    AND pr.orientation IN ('hetero', 'bi')

    GROUP BY ph.ID HAVING distance < 10 AND age >= 16 

    ORDER BY RAND() LIMIT 1

好吧,我写了一个“group by”子句,只返回我需要显示的信息行(距离,年龄,成员ID,照片ID等)。 问题是,当几个成员已经对相同的照片进行排名时,该查询可以返回用户已经排名的照片。 我发现这是因为当我说“其中rk.ID_membre&lt;&gt;'96'或ISNULL(注意)” 我对mysql说“你可以返回一张照片,如果它还没有标记,或者你找到的第一个标记与'96'不同”。怎么说“你可以返回,如果它没有标记或如果有,所有的标记必须与'96'不同。”

我需要一个SQL函数作为COUNT或AVG,如果在agregated列中是否存在int,则返回该函数。我会做某事

  SELECT .. all the other infos .., 
IS_THERE('96' IN photo) AS 'already_ranked', 
IS_THERE('96' IN signalements) 'already_reported' 
    ..blablabla...
    WHERE/HAVING already_reported = 0 AND already_ranked = 0
    GROUP BY photos.ID

不要犹豫,告诉我是否有更快或更简单的方法来进行此查询。

1 个答案:

答案 0 :(得分:1)

考虑:

SELECT `id`, SUM(CASE WHEN LOCATE('96', `field`) > 0 THEN 1 ELSE 0 END) AS cnt
FROM `table`
GROUP BY `id`