SQL选择具有不同限制的多表

时间:2015-12-02 16:55:24

标签: mysql sql database

我想通过 P_id 选择所有类别,并加入数据表 现在其他想要 p_id 每行从数据表

中选择

类别表

id  | p_id  |  cat_name
----+-------+------------------------
1   | 1     |  Bookenter code here
2   | 1     |  Music
3   | 1     |  Game
4   | 1     |  Apps

数据表

=====================================
id  |  cat_id   |  data
----+-----------+--------------------
1   |  1        |  Book Data ... ...
2   |  1        |  Book Data ... ...
3   |  1        |  Book Data ... ...
4   |  1        |  Book Data ... ...
5   |  1        |  Book Data ... ...
6   |  1        |  Book Data ... ...
7   |  1        |  Book Data ... ...
... More ... More ... More ...

我想要这样每行cat_table data_table 3行选择

============================================================
cat_name  |  data
----------+--------------------------
Book      |  Book Data ... ...
Book      |  Book Data ... ...
Book      |  Book Data ... ...
-------------------------------------
Music     |  Music Data ... ...
Music     |  Music Data ... ...
Music     |  Music Data ... ...
-------------------------------------
Game      |  Game Data ... ...
Game      |  Game Data ... ...
Game      |  Game Data ... ...
... More ... More ... More ...

我想要这个(或){group_concat}

=========================================
cat_name  |  data
----------+------------------------------------------------------------
Book      | Book Data ... ...  | Book Data ... ... | Book Data ... ...
Music     | Music Data ... ... | Music Data ... ...| Music Data ... ...
Game      | Game Data ... ...  | Game Data ... ... | Game Data ... ...
... More ... More ... More ...

我想选择所有类别按 P_id 并加入数据表现在其他想要 p_id 每行从中选择三个行数据表

任何人都可以帮助我

1 个答案:

答案 0 :(得分:2)

希望这能解决您的问题

SELECT
    sq.category,
    sq.data
FROM (
    SELECT
        DATA.*,
        cats.name AS category,
        row_number() over(PARTITION BY cat_id ORDER BY cat_id DESC) AS ROW_COUNT FROM `data`
    INNER JOIN cats ON data.cat_id = cats.id
    ) AS sq
WHERE
    ROW_COUNT <= 3

在查询中...... ROW_COUNT <= 3您可以设置选择限制。