如何跟踪二级索引ID

时间:2014-02-15 15:20:04

标签: php mysql

拥有一个将由多个用户共享的表。基本的表结构将是:

unique_id | user_id  | users_index_id | data_1 | data_2 etc etc

id字段为int类型,unique_id为自动增量的主键。

数据类似于:

unique_id | user_id | users_index_id
1 | 234 | 1
2 | 234 | 2
3 | 234 | 3
4 | 234 | 4
5 | 732 | 1
6 | 732 | 2
7 | 234 | 5
8 | 732 | 3

如何跟踪'users_index_id',以便专门为user_id“自动递增”?

非常感谢任何帮助。正如我寻找答案但不确定我是否使用正确的术语来找到我需要的答案。

2 个答案:

答案 0 :(得分:3)

始终如一地执行此操作的唯一方法是使用“before insert”和“before update”触发器。 MySQL不直接支持这种语法。您可以在存储过程中将所有更改包装到表中并将逻辑放在那里,或者在执行insert时使用非常谨慎的逻辑:

insert into table(user_id, users_index_id)
    select user_id, count(*) + 1
    from table
    where user_id = param_user_id;

但是,如果您执行delete或某些更新,这将无法保持秩序。

您可能会发现在查询时而不是在数据库中计算users_index_id会更方便。您可以使用子查询(可能在表上使用正确的索引)或使用变量(可能更快但无法放入视图中)来执行此操作。

如果您在table(user_id, unique_id)上有索引,则以下查询应该可以正常运行:

select t.*,
       (select count(*) from table t2 where t2.user_id = t.user_id and t2.unique_id <= t.unique_id
       ) as users_index_id
from table t;

你需要非极端表现的指数。

答案 1 :(得分:0)

您需要找到MAX(users_index_id)并将其递增1。为避免必须手动锁定表以确保唯一键,您需要在SELECT语句中执行INSERT但是,MySQL在执行INSERTUPDATE语句时不允许您引用目标表,除非它包含在子查询中:

INSERT INTO users (user_id, users_index_id) VALUES (234, (SELECT IFNULL(id, 0) + 1 FROM (SELECT MAX(users_index_id) id FROM users WHERE user_id = 234) dt))

<击>

没有subselect的查询(感谢Gordon Linoff):

INSERT INTO users (user_id, users_index_id) SELECT 234, IFNULL((SELECT MAX(users_index_id) id FROM users WHERE user_id = 234), 0) + 1;

http://sqlfiddle.com/#!2/eaea9a/1/0