1

我有一个数据库,其中有groups很多users(1:N)。这两个表旨在为每个组提供唯一 ID,为每个用户提供唯一 ID。但是现在我遇到了一个问题,我需要选择一个组的 ID 以及该组中用户的 ID(这与他的真实数据库 ID 不同)。是否有某种方法可以在 MySQL 中选择这些子 ID 而无需实际更改用户表结构?

我当前的表结构是什么样的:

-----------------
| GROUPS        |
=================
| ID PK AUTO_INC|
| NAME          |
| DESCRIPTION   |
| ...other      |
| non-related   |
| columns       |
-----------------

------------------
| USERS          |
==================
| ID PK AUTO_INC |
| NAME           |
| GROUP          |
| AGE            | 
|...other        |
| non-related    |
| columns        |
------------------

编辑:我想要的看起来像这样:

GROUPS
----------------------------------
| ID  | Name | Description | ... |
==================================
| 1   |  A   | First one   | ... |
| 2   |  B   | Second one  | ... |
| 3   |  C   | Third one   | ... |
----------------------------------
USERS
--------------------------------------
| ID  | Name    | Group  | Age | ... |
======================================
| 1   |  John   |   1    | 35  | ... |
| 2   |  Adam   |   1    | 22  | ... |
| 3   |  Bob    |   2    | 18  | ... |
| 4   |  Jane   |   1    | 38  | ... |
| 5   |  Emma   |   2    | 56  | ... |
| 6   |  Aaron  |   3    | 26  | ... |
| 7   |  Alice  |   2    | 48  | ... |
--------------------------------------

And as a result I would like to get:
-----------------------------------
| GID | UID| Name    |  Age | ... |
===================================
| 1   | 1  |  John   |  35  | ... |
| 1   | 2  |  Adam   |  22  | ... |
| 1   | 3  |  Jane   |  38  | ... |
| 2   | 1  |  Bob    |  18  | ... |
| 2   | 2  |  Emma   |  56  | ... |
| 2   | 3  |  Alice  |  48  | ... |
| 3   | 1  |  Aaron  |  26  | ... |
-----------------------------------

我希望现在它会有意义。提前致谢。

4

1 回答 1

0

我知道如何做到这一点的唯一方法是使用变量

select
    t.id,
    t.name,
    t.group,
    t.rank as newid
from ( 
    select
        u.id,
        u.name,
        u.group,
        If(@group <> u.`Group`, @rownum := 1, @rownum := @rownum + 1) AS rank, 
        @group := u.`Group`
    from
        Users u 
            cross join (
            select
                @rownum := NULL,
                @group := 0
        ) as r 
    order by
        u.group,
        u.id
    ) as t
order by 
    t.group,
    t.id;

这种方法不能保证有效,但在实践中似乎有效。

Example SQLFiddle

于 2013-11-12T00:05:35.717 回答