在每个类别中选择2行

时间:2016-08-07 09:28:04

标签: mysql

我有以下查询。

此查询将在每个industry_id中获取2行。因此,如果有10个唯一的industry_id方法,则Query应从每个industry_id返回2行。

SET @a := 0;

SELECT
    *
FROM
    (
        SELECT
            @a :=@a + 1 AS row_count,
            p.*, u.first_name,
            u.designation,
            u.profile_picture,
            i. NAME AS industry,
            l.location
        FROM
            industry i,
            projects p,
            location l,
            user_profile u
        WHERE
            u.uid = p.uid
        AND p.location_id = l.id
        AND i.id = p.industry_id
        AND p.abstract != ''
    ) t
WHERE   row_count <= 2

但是这个查询总是只从一个industry_id返回2行。

如何从每个industry_id获得2行

1 个答案:

答案 0 :(得分:1)

请试一试:

SELECT
    *
FROM
    (
        SELECT
            IF(i.id = @sameIndustryId, @a :=@a + 1, @a := 1) AS row_count,
            @sameIndustryId := i.id,
            p.*, u.first_name,
            u.designation,
            u.profile_picture,
            i. NAME AS industry,
            l.location
        FROM
            industry i,
            projects p,
            location l,
            user_profile u,
           (SELECT @a := 1, @sameIndustryId := 0 ) var
        WHERE
            u.uid = p.uid
        AND p.location_id = l.id
        AND i.id = p.industry_id
        AND p.abstract != ''
        ORDER BY i.id
    ) t
WHERE   row_count <= 2

注意:尽量避免IMPLICIT加入。当您尝试在3个或更多表之间建立关系时,不清楚。更好地使用INNER JOIN。因为它表现出更好的关系。

SELECT
    *
FROM
    (
        SELECT
            IF(i.id = @sameIndustryId, @a :=@a + 1, @a := 1) AS row_count,
            @sameIndustryId := i.id,
            p.*, u.first_name,
            u.designation,
            u.profile_picture,
            i. NAME AS industry,
            l.location
        FROM industry i
                INNER JOIN projects p ON i.id = p.industry_id
        INNER JOIN location l ON p.location_id = l.id
        INNER JOIN user_profile u ON u.uid = p.uid
        CROSS JOIN (SELECT @a := 1, @sameIndustryId := 0 ) var
        WHERE p.abstract != ''
        ORDER BY i.id
    ) t
WHERE   row_count <= 2;