SQL 合并两个表 - 每个键值只得到一行

SQL merge two tables - get only one row for each key value

我正在尝试 运行 我的数据库上的 SQL 命令。我有两张表,一张给用户,另一张给 posts。我想找到每个用户的最后一个 post。我试过以下:

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`

失败并出现错误 "your syntax is weird near GROUP BY b.username on line 5"。 我尝试 运行 使用 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 | .... |
+----+----------+------+------+

顺序正确,我只想要每个用户的上一行。如果有任何帮助,我将不胜感激。

您实际上需要过滤,而不是分组。您可以使用相关子查询执行此操作:

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中,您可以使用window函数:

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