SQL合并两个表-每个键值仅获得一行

问题描述 投票:0回答:1

我正在尝试在数据库上运行SQL命令。我有两个表,一个用于用户,另一个用于帖子。我想查找每个用户的最新帖子。我尝试了以下内容:

SELECT b.`username`, b.`id`, c.`home`, c.`text` FROM `sunlight-users` AS b 
LEFT JOIN `sunlight-posts` AS c ON b.`id` = c.`author`
WHERE b.`group` = 1 OR b.`group`=3 OR b.`group`= 5 OR b.`group` = 10 OR b.`group` = 14 OR b.`group` = 
23 OR b.`group` = 25
ORDER by c.`time` DESC
GROUP BY b.`username`

它失败,并出现错误“您的语法在第5行的GROUP BY b。username附近很奇怪”。我试图使用while循环(在网页上)运行命令,如下所示:

$query = DB::query("SELECT * FROM `"._mysql_prefix."-users` WHERE `group` = 1 OR `group` = 3 OR `group` = 5 OR `group` = 10 OR `group` = 14 OR `group` = 23 OR `group` = 25");

    while($item = DB::row($query)) {
        $post = DB::query("SELECT type,home,xhome,author,time FROM `"._mysql_prefix."-posts` WHERE ".$knihy." AND `author` = ".item['id']." ORDER BY `time` DESC LIMIT 1");
        switch($post['home']){
            case 2:
           //code
                break;

            case 3:
             //code
            break;

            default:
             //code
        }

但是看起来第二个查询被完全忽略了,即使手动将查询键入数据库的值为2或3,我也得到默认值。我知道像在循环中运行50个查询可能不是一个好主意,这就是为什么我正在尝试一次完成所有操作。此代码:

SELECT b.`username`, b.`id`, c.`home`, c.`text` FROM `sunlight-users` AS b 
    LEFT JOIN `sunlight-posts` AS c ON b.`id` = c.`author`
    WHERE b.`group` = 1 OR b.`group`=3 OR b.`group`= 5 OR b.`group` = 10 OR b.`group` = 14 OR b.`group` = 
    23 OR b.`group` = 25
    ORDER by c.`time` DESC

结果

id       username         home           text
1        user1            2              ....
1        user1            3              aaaa
0        user0            4              ....

顺序正确,我只希望每个用户的上一行。我将不胜感激。

mysql sql join greatest-n-per-group
1个回答
0
投票

您实际上需要过滤,而不是分组。您可以使用相关的子查询来做到这一点:

select 
    u.username, 
    u.id, 
    p.home, 
    p.text 
from sunlight_users u
left join sunlight_posts p
    on  u.id = p.author
    and p.time = (select max(p1.time) from sunlight_posts p1 where p1.author = u.id)
where u.group in (1, 3, 5, 10, 14, 23, 25)
order by u.username

在MySQL 8.0中,您可以使用窗口函数:

select *
from (
    select 
        u.username, 
        u.id, 
        p.home, 
        p.text,
        row_number() over(partition by u.id order by p.time desc) rn
    from sunlight_users u
    left join sunlight_posts p on  u.id = p.author
    where u.group in (1, 3, 5, 10, 14, 23, 25)
) t
where rn = 1
order by u.username
© www.soinside.com 2019 - 2024. All rights reserved.