如何将GROUP BY放在sql语句中?

时间:2014-04-03 09:55:33

标签: php mysql sql join group-by

 $strSQL = "SELECT * FROM user, education, preference, additional, experience
        WHERE

        user.user_idx = education.edu_user AND 
        education.edu_user = preference.pref_user AND 
        preference.pref_user = additional.add_user AND 
       additional.add_user = experience.exp_user AND "
     .$user_sql_join.$edu_sql_join.$pref_sql_join.$add_sql_join.$exp_sql_join.$select_none_sql;

我不知道如何在以下SQL语句中包含GROUP BY。请帮我解决这个问题。我正在使用JOIN语句执行搜索功能。

3 个答案:

答案 0 :(得分:0)

您只能使用GROUP BY后指定的字段在查询末尾添加SELECT。您不能将其与SELECT * ...

一起使用

例如 -

SELECT user.user_idx FROM user, education, preference, additional, experience
        WHERE

        user.user_idx = education.edu_user AND 
        user.user_idx= preference.pref_user AND 
        preference.pref_user = additional.add_user AND 
       additional.add_user = experience.exp_user 
GROUP BY user.user_idx

此查询会按user.user_idx字段

对结果进行分组

答案 1 :(得分:0)

获取user.user_idx

的结果
SELECT user.user_idx FROM user, education, preference, additional, experience
        WHERE

        user.user_idx = education.edu_user AND 
        user.user_idx= preference.pref_user AND 
        preference.pref_user = additional.add_user AND 
       additional.add_user = experience.exp_user 
GROUP BY user.user_idx

答案 2 :(得分:0)

您需要某种形式的聚合,如SUM()AVG()MAX()等,以使用GROUP BY。 例如

SELECT COUNT(user.user_idx) FROM user, education, preference, additional, experience
WHERE
user.user_idx = education.edu_user AND 
education.edu_user = preference.pref_user AND 
preference.pref_user = additional.add_user AND 
additional.add_user = experience.exp_user
GROUP BY education.edu_idx

这将为您提供每个education.edu_idx的用户计数,假设user_idx和edu_id

如果没有聚合,GROUP BY不会做太多:如果你没有聚合,你可能应该尝试排序。即使用SORT BY