是否可以在具有限制条件的同一列上将GROUP BY与GROUP_CONCAT一起使用

时间:2018-10-05 11:37:54

标签: mysql join subquery

SELECT id,businessName,GROUP_CONCAT(id) FROM tbl_business LIMIT 0,1

上面的查询给了我以下结果

1   Camp San Fransisco  1,4

现在,如果我对相同的查询应用GROUP BY并进行限制,则GROUP_CONCAT列将不会提供与以前相同的结果。

SELECT id,businessName,GROUP_CONCAT(id) FROM tbl_business GROUP BY id LIMIT 0,1

查询结果

1   Camp San Fransisco  1

我正在使用GROUP BY id来获取具有where条件的唯一记录。

是否可以将GROUP_BY与GROUP_CONCAT结合使用,或者还有其他适用于MySQL的方法?

我想保留带有ID的第一个查询结果,因此,如果可能的话,我只需要基于第一个结果ID调用第二个查询。由于多个表的LEFT JOIN和某些SUB QUERY依赖于它,因此我无法删除GROUP BY ID

以上查询仅出于解释目的,原始查询要长得多。

实际查询:

SELECT bs.id,bs.businessName,bs.businessDesc,bs.latitude,bs.longitude,bs.slug,bs.contactNo,bs.location,bs.isAddedBy,bs.createdDate,cat.categoryName as category,GROUP_CONCAT(DISTINCT(bcat.categoryName) SEPARATOR ', ') as subcategory,
        (SELECT COUNT(id) FROM tbl_reviews WHERE referenceId = bs.id) as totalReview,
        (SELECT CEIL(AVG(rating)) FROM tbl_reviews WHERE referenceId = bs.id) as avgRating,
        (SELECT imageName FROM tbl_business_images as bimg WHERE bimg.businessId = bs.id LIMIT 1) as bImage,

        (
            (ACOS
                (
                    SIN(37.09024 * PI() / 180) * SIN(bs.latitude * PI() / 180) + COS(37.09024 * PI() / 180) * COS(bs.latitude * PI() / 180) * COS(
                                (-95.712891 - bs.longitude) * PI() / 180)
                )* 180 / PI()
            ) * 60 * 1.1515 * 1.609344
        ) as distance,

        (SELECT 
                (DATEDIFF(bs.createdDate,NOW()) * 5) + 
                ((SELECT COUNT(id) FROM tbl_business_images WHERE businessId = bs.id) * 2) + 
                ((SELECT count(id) FROM tbl_business_views WHERE businessId = bs.id) * 2) + 
                ((SELECT COUNT(id) FROM tbl_reviews WHERE referenceId = bs.id) * 10)) 
        as totalPoint
        FROM tbl_business as bs
        LEFT JOIN tbl_category as cat
        ON bs.businessCat = cat.id
        LEFT JOIN tbl_business_subcategories as bsubs
        ON bs.id = bsubs.businessId
        LEFT JOIN tbl_category as bcat
        ON bsubs.subcategoryId = bcat.id
        WHERE bs.isActive = 'y' 
        GROUP BY bs.slug

当前查询输出:

id  businessName  businessDesc  latitude  longitude slug  contactNo location  isAddedBy createdDate category  subcategory totalReview avgRating bImage  distance  totalPoint  

1   test  test   45.14  -122.82   test   1234567890  USA  c   2018-09-29 11:38:58   Category   Subcategory1,subcategory2   1   5   image.png  2382.763331498852   -4

感谢您的帮助。

0 个答案:

没有答案