问题
To illustrate my problem I will use the analogy of authors and books.
I have 2 tables "author" and "books". Authors are unique and books are tied to a specific authors using a foreign key constraint.
I was wondering if it was possible to have a column called "booknum" in the "books" table that auto-increment within the subset of a single author. So if the table has 100 rows and im inserting the 4th book of an author it puts a 4 into the "booknum" column.
For example if the books table had 6 rows:
id | authors_id | booknum | name
1 | 1 | 1 | "hello"
2 | 1 | 2 | "goodbye"
3 | 2 | 1 | "booktitle"
4 | 3 | 1 | "more title"
5 | 1 | 3 | "nametwo"
6 | 2 | 2 | "nameone"
Is this possible within mysql or do I need to go and check for the last created book and manually increment when I add a book?
回答1:
You could use a trigger:
CREATE TRIGGER biBooks
BEFORE INSERT ON books
FOR EACH ROW SET NEW.booknum = (
SELECT COALESCE(MAX(booknum), 0) + 1
FROM books
WHERE authors_id = NEW.authors_id
)
;
回答2:
Single-table syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
Multiple-table syntax:
UPDATE [LOW_PRIORITY] [IGNORE] table_references
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
For the single-table syntax, the UPDATE statement updates columns of existing rows in the named table with new values. The SET clause indicates which columns to modify and the values they should be given. Each value can be given as an expression, or the keyword DEFAULT to set a column explicitly to its default value. The WHERE clause, if given, specifies the conditions that identify which rows to update. With no WHERE clause, all rows are updated. If the ORDER BY clause is specified, the rows are updated in the order that is specified. The LIMIT clause places a limit on the number of rows that can be updated.
For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions. Each matching row is updated once, even if it matches the conditions multiple times. For multiple-table syntax, ORDER BY and LIMIT cannot be used.
来源:https://stackoverflow.com/questions/10879104/how-auto-increment-within-a-subset-of-the-table-mysql