以下是我的bill_detail表,其中我存储了用户购买物品的账单
create table bill_details(
bill_no bigint(20) unsigned NOT NULL AUTO_INCREMENT,
customer_id bigint(20) unsigned NOT NULL,
sub_total decimal(15,2),
vat decimal(15,2),
total decimal(15,2),
payment_type varchar(30) NOT NULL,
status varchar(20),
add_date timestamp DEFAULT 0,
CONSTRAINT fk_cust1 FOREIGN KEY (customer_id)
REFERENCES customer_details(id),
cid bigint(20) unsigned NOT NULL,
CONSTRAINT cli_fk15 FOREIGN KEY (cid) REFERENCES client (id) ON DELETE CASCADE ON UPDATE CASCADE,
primary key(bill_no))ENGINE=InnoDB DEFAULT CHARSET=utf8;
这里有多个用户同时使用我的应用程序。我的问题是用户没有获得序列式的账单号。
我该如何解决这个问题?
答案 0 :(得分:0)
好吧,请考虑以下内容......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,user_id INT NOT NULL, bill_no INT NULL);
INSERT INTO my_table (user_id) VALUES (1),(1),(2),(1),(2),(3),(1),(2),(3),(1),(4);
SELECT * FROM my_table;
+----+---------+---------+
| id | user_id | bill_no |
+----+---------+---------+
| 1 | 1 | NULL |
| 2 | 1 | NULL |
| 3 | 2 | NULL |
| 4 | 1 | NULL |
| 5 | 2 | NULL |
| 6 | 3 | NULL |
| 7 | 1 | NULL |
| 8 | 2 | NULL |
| 9 | 3 | NULL |
| 10 | 1 | NULL |
| 11 | 4 | NULL |
+----+---------+---------+
SELECT x.*
, COUNT(*) rank
FROM my_table x
JOIN my_table y
ON y.user_id = x.user_id
AND y.id <= x.id
GROUP
BY x.user_id
, x.id;
+----+---------+---------+------+
| id | user_id | bill_no | rank |
+----+---------+---------+------+
| 1 | 1 | NULL | 1 |
| 2 | 1 | NULL | 2 |
| 4 | 1 | NULL | 3 |
| 7 | 1 | NULL | 4 |
| 10 | 1 | NULL | 5 |
| 3 | 2 | NULL | 1 |
| 5 | 2 | NULL | 2 |
| 8 | 2 | NULL | 3 |
| 6 | 3 | NULL | 1 |
| 9 | 3 | NULL | 2 |
| 11 | 4 | NULL | 1 |
+----+---------+---------+------+
UPDATE my_table a
JOIN
( SELECT x.*,COUNT(*) rank
FROM my_table x
JOIN my_table y
ON y.user_id = x.user_id
AND y.id <= x.id
GROUP
BY x.user_id
, x.id
) b
ON b.id = a.id
SET a.bill_no = b.rank
WHERE a.bill_no IS NULL; -- <-- You may want to discard or rethink this line
SELECT * FROM my_table;
+----+---------+---------+
| id | user_id | bill_no |
+----+---------+---------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 1 | 3 |
| 5 | 2 | 2 |
| 6 | 3 | 1 |
| 7 | 1 | 4 |
| 8 | 2 | 3 |
| 9 | 3 | 2 |
| 10 | 1 | 5 |
| 11 | 4 | 1 |
+----+---------+---------+
编辑:每个用户最新的bill_no ...
SELECT x.*
FROM my_table x
JOIN
( SELECT user_id,MAX(bill_no) max_bill_no FROM my_table GROUP BY user_id ) y
ON y.user_id = x.user_id
AND y.max_bill_no = x.bill_no;
+----+---------+---------+
| id | user_id | bill_no |
+----+---------+---------+
| 8 | 2 | 3 |
| 9 | 3 | 2 |
| 10 | 1 | 5 |
| 11 | 4 | 1 |
+----+---------+---------+