SQL连接和分组问题

发布于 2024-10-14 01:39:45 字数 883 浏览 2 评论 0原文

首先要说的是,我正在使用 mySQL,并且访问数据库的唯一方法是通过 phpMyAdmin,因为这是针对网站的。

首先,我有一个像这样的用户表(表1):

user_id | name
--------------
      1 | Mike
      2 | Johny
      3 | Bob

还有另一个关于他们的赛季结果的表(表2):

user_id | season | result
-------------------------
      1 | 2009   |     10
      1 | 2010   |      8
      1 | 2011   |      5
      2 | 2009   |      7
      2 | 2010   |      3
      3 | 2009   |      1

现在我想要用户的名字和他上赛季的结果,所以像这样:

user_id | name | season | result
--------------------------------
      1 | Mike |   2011 |      5
      2 | Johny|   2010 |      3
      3 | Bob  |   2009 |      1

我最接近的东西就像这样,

SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id

但我无法提供我想要最新一季的信息,它只是使用随机的一季。 任何人有任何想法如何做到这一点?

此致, 洛克

First to say I'm using mySQL and my only way of accessing database is over phpMyAdmin since this is for a website.

First I have a table of users like this (table1):

user_id | name
--------------
      1 | Mike
      2 | Johny
      3 | Bob

and another table about their season results (table2):

user_id | season | result
-------------------------
      1 | 2009   |     10
      1 | 2010   |      8
      1 | 2011   |      5
      2 | 2009   |      7
      2 | 2010   |      3
      3 | 2009   |      1

And now I want out the user's name and his last season's result, so something like this:

user_id | name | season | result
--------------------------------
      1 | Mike |   2011 |      5
      2 | Johny|   2010 |      3
      3 | Bob  |   2009 |      1

The closest I have come to something like this was

SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id

But I cannot provide that I want the newest season and it just uses a random one.
Anyone has any ideas how to do this?

best regards,
Rok

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

罪歌 2024-10-21 01:39:45
SELECT *
FROM table1, table2,
(SELECT user_id AS lUserid, MAX(season) AS lSeason FROM table2 GROUP BY user_id) AS lTable2
WHERE table1.user_id = table2.user_id
AND table2.user_id = lTable2.lUserid
AND table2.season = lTablle2.lSeason
SELECT *
FROM table1, table2,
(SELECT user_id AS lUserid, MAX(season) AS lSeason FROM table2 GROUP BY user_id) AS lTable2
WHERE table1.user_id = table2.user_id
AND table2.user_id = lTable2.lUserid
AND table2.season = lTablle2.lSeason
深者入戏 2024-10-21 01:39:45

您是否尝试过按季节栏排序?

SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id ORDER BY season DESC

Have you tried to order them by Season column?

SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id ORDER BY season DESC
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文