I am not entirely sure what to search so I apologize if this is in fact a duplicate.
I have a table (or at least would like to) as follows:
ID
Company Name
SomeOtherInfo
The primary key would be ID and Company name (composite primary key). What I would like is so that the ID auto increments on each company.
Ex:
1-google
2-google
3-google
1-yahoo
4-google
2-yahoo
This way they are always unique, but each one increments for each company individually.
Is this possible from simple SQL create commands, would rather not have 2 tables and join them using a secondary ID.
Let me know, thanks.
If I follow the question. Create a single table with an identity on the ID column. Then create a unique index on the Company Name.
MySql Version
CREATE TABLE Company (
CompanyID int NOT NULL AUTO_INCREMENT,
CompanyName varchar(255) NOT NULL,
OtherData varchar(255),
PRIMARY KEY (CompanyID)
);
CREATE UNIQUE INDEX CompanyUniqueComposite
ON Company (CompanyID , CompanyName );
Related
At a workplace they recycle punchcard ids (for some strange reason). So it is common to have past employees clashing with current employees. As a workaround I want to have employee punchcard id, employee name+surname as the unique primary key (fingers crossed, perhaps add date-of-birth and even passport if available). That can be accomplished with
PRIMARY KEY (pid,name,surname).
The complication is that another table now wants to reference an employee by its above primary key.
Alas, said PK has no name! How can I reference it?
I tried these but no joy:
PRIMARY KEY id (pid, name, surname),
INDEX id (pid, name, surname),
PRIMARY KEY id,
INDEX id (pid, name, surname) PRIMARY KEY,
Can you advise on how to achieve this or even how to reference a composite primary key?
Update:
The table to store employees is em.
The table which references an employee is co (a comment made by an employee).
Ideally I would use pid (punchcard id) as the unique id of each employee. But since pids are recycled, this is not unique. And so I resorted to creating a composite key or an index which will be unique and can reference that as a unique employee id. Below are the 2 tables without the composite key. For brevity, I abbreviated table names and omitted surname etc. So the question is, how can I reference an employee whose id is composite from another table co.
CREATE TABLE em (
pid INT NOT NULL,
name VARCHAR(10) NOT NULL
);
CREATE TABLE co (
id INT primary key auto_increment,
em INT,
content VARCHAR(100) NOT NULL,
constraint co2em_em_fk foreign key (em) references em(pid)
);
If another table wants to reference this one by a composite key, you don't need it to have a name - just the list of fields will do. E.g.
CREATE TABLE other_table (
ID INT PRIMARY KEY AUTO_INCREMENT,
pid *defintion*,
name *defintion*,
surname *defintion*,
..., -- other fields, keys etc.
FOREIGN KEY (pid, name, surname) REFERENCES employees(pid, name, surname)
);
UPD: If you expect that the set of the fields inside PK might change and you can't make a simpler PK (auto-increment integer for example) for the original table, then your best bet might be something like this:
CREATE TABLE employee_key (
ID INT PRIMARY KEY AUTO_INCREMENT,
pid *defintion*,
name *defintion*,
surname *defintion*,
FOREIGN KEY (pid, name, surname) REFERENCES employees(pid, name, surname)
);
-- and then reference the employees from other tables by the key from employee_key:
CREATE TABLE other_table(
ID INT AUTO_INCREMENT PRIMARY KEY,
employee_id INT NOT NULL,
... -- other fields, indexes, etc...
FOREIGN KEY (employee_id) REFERENCES employee_key(ID)
);
Then if you have a change in employee table PK, you'll only need to update employee itself and employee_key, any other tables would stay as is.
If you CAN, however, change the original employees table, I would recommend something like this:
CREATE TABLE employees(
ID INT PRIMARY KEY AUTO_INCREMENT,
pid *defintion*,
name *defintion*,
surname *defintion*,
... -- other fields, keys, etc.
UNIQUE KEY (pid, name, surname)
);
Then you'll have to maintain the logic of generating new pid's in your code, though, or have them in some side table.
UPD2: Regarding inserts and updates.
As for inserts: you need to insert these explicitly - otherwise how would you expect the relation to be established? If you're using an ORM library to communicate with your database, then it might provide you with the methods to specify linked objects without explicitly adding the IDs, but otherwise to insert a row into employees, employee_key and other_table you need to first INSERT INTO employees(...) ;, then get perform a separate INSERT for the employee_key (knowing the key fields you've just added to employees), get the auto-generated key from employee_key and then use that to perform inserts to any other tables.
You might simplify all this by writing an AFTER INSERT trigger for employees table (that would automatically create a row in employee_key) and/or performing your inserts via a stored procedure (that will even return back the key of the newly inserted row in employee_key). But still this work needs to be done, MySQL won't do it for you by default.
Updates are a bit easier, since you can specify ON UPDATE CASCADE when adding the foreign key - in that case a change to one of the fields in the employees will automatically trigger the same change in any tables that reference employees by this key.
You would define it
CONSTRAINT id
PRIMARY KEY (pid, name, surname)
But you should read more about how MySQL uses INDEXES and how to optimize them
https://dev.mysql.com/doc/refman/8.0/en/optimization-indexes.html
guys i was asked to make the design for product table like this
product_code (PK)----------varchar2(5)
product_name---------------varchar2(15)
product_type---------------varchar2(1)
but i want to make an ID auto increment column to be primary key as well to be accessed within any CRUD operations .. can i do this with the existence of primary key product_code ?... or the ID column is useless here ??
Make the product_id the primary key as an auto_increment column.
You can then define product_code as unique and not null.
Foreign key relationships should use the product_id column.
If you've been given requirements that state your primary key should be a varchar2(5) called product_code. I would recommend following the requirements, I see no practical reason to object.
Do you know how many records will exist in this table, do you have reason to believe the requirements provided will introduce an issue? If so document your concerns and ask for clarification, but you appear to be a contractor and I would defer to the customer.
Only the primary key can be auto-generated in MySQL.
Create the table with a new ID column that is auto-generated and make your existing PRODUCT_CODE column unique, as in:
create table product (
id int primary key not null auto_increment,
product_code varchar(5) not null,
product_name varchar(15) not null,
product_type varchar(1),
constraint uq_code unique (product_code)
);
In SQL i have a table for users. On my website i want people be able to make groups consisting of 2 or more users, but i have no idea how to store that. People can be a part of multiple groups at the same time. If i'd make a table groups, how could i store it's members in that table?
You would have a table groups and one called userGroups. These would look like:
create table groups (
groupId int auto_increment primary key,
groupName varchar(255)
);
create table userGroups (
userGroupId int auto_increment primary key,
userId int not null,
groupId int not null,
foreign key (userId) references users(userId),
foreign key (groupId) references groups(groupId)
);
What you're describing is called a many-to-many relationship, and it requires a third table:
UserTable: UserID (unique), UserName, etc.
GroupTable: GroupID (unique), GroupName, etc.
UserGroups: UserGroupID (unique), UserID, GroupID
With a third table holding the primary key(pk)) of a group and a pk of a person. These columns are the pk of the table. You can have other to
Columns too, e.g. date joined or whatever. You have one row in this table per person/group.
It's a common concept/pattern so make sure you learn and understand it.
I need to create a table called benificiaries where I have three columns
customerid
accountno
bank
The condition should be one customerid can have only one unique accountno. But another customerid can have the same accountno and same unique (only once). So I cant give primary key to accountno. Even for customerid I can't give primary key, since one customerid can have multiple records with unique accountno.
How can we create table in this case? Any ideas?
You can use multiple-column unique index.
CREATE TABLE YOUR_TABLE (
id INT NOT NULL AUTO_INCREMENT,
customerid INT NOT NULL,
accountno INT NOT NULL,
bank INT NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX name (customerid,accountno)
);
Documentation here.
https://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html
If one customerid can have only 1 unique account number then how can you expect duplicates in terms of customer id in that table?
You can simply set a primary key to another column and make the customerid unique. I think this is what you want to have. Now every customerid is unique, but many costomerids can have the same accountno.
CREATE TABLE benificiaries(
id INT PRIMARY KEY,
customerid INT NOT NULL UNIQUE,
accountno INT NOT NULL,
bank INT NOT NULL
);
database can't manage all the business constraints within the data model. For the case, you might address elementary constraints with indexes (multiple column index for customerid, accountno and simple column index for accountno to perform search on the other way), add an auto-increment id and deal the business constraints in your code.
Just set your customer_id as a primary key then regarding the concept that a only two customer_id can have same account number once, will depend on the process of your App or System.
CREATE TABLE `tmpr_map`.`tbl_example`
(`customer_id` INT(11) NOT NULL AUTO_INCREMENT,
`account_number` VARCHAR NOT NULL , `bank_amount` DECIMAL(11,2) NOT NULL ,
PRIMARY KEY (`customer_id`)) ENGINE = InnoDB;
I have to design a database where some information about usage of printer resource is to be recorded in a mysql database. What is the best way to design the database?
I do not want to create a table for each student as there would be around 6000 tables and which would keep growing each year if archives are to be maintained. Also it is difficult to create tables based on registration number of student. Is there a better way than storing multivalued attribute for details of printing. Please suggest some solutions. Also querying should be effective.
There is no need to create different tables for each student.
Just create a Table STUDENT which will contain the personal details of the student identified by their Registration number (lets say Regno-PrimaryKey).
And then another Table RESOURCE, which will have the following schema:
-RecNo Integer PK
-StudentID Foriegn key referenced to Regno in the Student Table
-Usage
or Data,Time(if you require)
This will work for and you need not have to create 6000 or more tables.
You have given very few information, but here is a shot:
create table student
(
registration_no varchar(50) not null primary key,
first_name varchar(50),
last_name varchar(50),
registration_year integer not null
);
create table printer
(
printer_id integer not null primary key,
printer_name varchar(50) not null,
ip_address varchar(50) not null,
queue_name varchar(50) not null
);
create unique index idx_printer_name on printer (printer_name);
create table printer_usage
(
usage_id integer not null primary key,
student_reg_no integer not null,
printer_id integer not null,
usage_date datetime not null,
pages integer not null
);
alter table printer_usage
add constraint fk_usage_student
foreign key (student_reg_no) references student (registration_no);
alter table printer_usage
add constraint fk_usage_printer
foreign key (printer_id) references printer (printer_id);
You will probably need to add more columns to the tables to store all the things you need. I was just guess stuff that you might want to store.