Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL查询从每个类别左连接中获取1个结果_Mysql - Fatal编程技术网

MySQL查询从每个类别左连接中获取1个结果

MySQL查询从每个类别左连接中获取1个结果,mysql,Mysql,我有10个帖子,每个帖子都有一个类别 Post Table ID| POST | 1 | post 1 | 2 | post 2 | 3 | post 3 | 4 | post 4 | 5 | post 5 | 6 | post 6 | 7 | post 7 | 8 | post 8 | 9 | post 9 | 10| post 10| Category table ID|Pid| Cate

我有10个帖子,每个帖子都有一个类别

Post Table
    ID| POST   |
    1 | post 1 |
    2 | post 2 |
    3 | post 3 |
    4 | post 4 |
    5 | post 5 |
    6 | post 6 |
    7 | post 7 |
    8 | post 8 |
    9 | post 9 |
    10| post 10|

Category table

    ID|Pid| Category
    1 | 1 | dog
    2 | 2 | dog
    3 | 3 | cat
    4 | 4 | cat
    5 | 5 | dog
    6 | 6 | horse
    7 | 7 | dog
    8 | 8 | cat
    9 | 9 | squirrel
    10| 10| dog
我试图从每个类别中只检索一个结果。类别将是动态的,所以我不能使用Where子句

Select * from posts parent
LEFT join categories child on child.parent_id=parent.id
如何更改查询以实现此目的


我应该得到post 1、post 3、post 6和post 9作为结果。

您可以使用聚合函数
min
为每个类别找到一个Pid,然后将其与posts表连接以获得所需的结果

select *
from post p
left join (
    select category, min(pid) pid
    from category
    group by category
    ) c on p.id = c.pid;

发布示例输入数据和所需结果为什么要“发布1、发布3、发布6和发布9”?