Issue in mysql table creation - mysql

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;

Related

Why does MySQL take unique index over primary index?

I have 2 very simple tables created as below:
create table company(
company_id int auto_increment,
company_no varchar(20),
company_name varchar(20),
primary key(company_id),
unique index uni_company_no(company_no)
);
create table department(
department_id int auto_increment,
department_no varchar(20),
department_name varchar(20),
company_id int not null,
primary key(department_id),
unique index uni_department_no(department_no),
index idx_company_id(company_id)
);
And if I query with the follwing SQL(I know it's an odd query), the result of EXPLAIN statenment shows that MySQL takes unique index(uni_company_no) instead of primary key:
explain select dept.* from department dept right join company com on dept.company_id = com.company_id;
EXPLAIN result
My questions are:
Why didn't MySQL use full table scan for table company?
Why didn't MySQL take primary key of table company if it decides to use index?
I'm very new to MySQL, so any input could be helpful. Thanks in advance.

How we can use the primary key in another table

I have Two table
customer table which has contained the information of the customer. But it has an account number we make a primary key of the account number.
And now the second Table is Bill Table.I've use the account number of the customer table when we update some information about the Bill table then will update is automatically of the particular account number
so, please tell me how we can resolve this problem, and how we can use
the foreign key of Bill table
I think what you are asking is how to update the Customer table at the same time when you are updating Bill table.
You can easily use a stored procedure to achieve this task. Within the stored procedure you can use transactions to make sure the 2nd update happens only if the first update is succeded. Otherwise, you can rollback.
So imagine that this is your customer table:
CREATE TABLE customer (
AccountNum int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (AccountNum)
);
PRIMARY KEY (AccountNum) > so you have a primary key in that table. Kudos!
CREATE TABLE BillTable (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
AccountNum int NOT NULL,
PRIMARY KEY (OrderID),
FOREIGN KEY (AccountNum) REFERENCES customer(AccountNum)
);
Now you linked customer and BillTable.

Primary Key in DB in SQL

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)
);

MySQL one to many with primary choice

Say I have a bunch of people with multiple phone numbers. In a MySQL database I'd have a Person table and a Phone Number table with a many to one relationship.
Now I want to make one of those numbers the primary phone number and only allow one primary number per person. How would I model this?
Try the schema below. It will prevent entries that try to assign more than one primary number per person.
CREATE TABLE person (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(50) NOT NULL,
`last_name` VARCHAR(50) NOT NULL,
PRIMARY KEY(`id`)
);
CREATE TABLE phonenumber (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`phonenumber` VARCHAR(10) NOT NULL,
`person_id` INT(11) UNSIGNED NOT NULL,
`is_primary` ENUM('1'),
PRIMARY KEY(`id`),
UNIQUE KEY idx_person_primary (`person_id`, `is_primary`),
UNIQUE KEY idx_person_phone (`phonenumber`, `person_id`)
);
INSERT INTO person (first_name, last_name) VALUES ('Michael', 'Jones');
INSERT INTO phonenumber (phonenumber, person_id, is_primary) VALUES ('9876543210', 1, 1);
INSERT INTO phonenumber (phonenumber, person_id, is_primary) VALUES ('1234567890', 1, NULL);
INSERT INTO phonenumber (phonenumber, person_id, is_primary) VALUES ('1234567891', 1, NULL);
This will allow the DB to police a single primary phone number for each person. For example if you try to assign another primary phone number to Michael Jones:
INSERT INTO phonenumber (phonenumber, person_id, is_primary) VALUES ('0123211234', 1, 1);
You will get a "Duplicate entry '1-1' for key 'idx_person_primary'" error.
http://sqlfiddle.com/#!9/dbb3c7/1
The "exactly one primary phone number" is tricky. One way uses triggers. Other databases offer expression-based indexes. This is tricky because:
The constraint spans two tables.
Guaranteeing exact "one-ness" across updates is tricky.
But one method in MySQL that comes close and doesn't use triggers:
create table persons (
personId int auto_increment primary key,
primary_personPhonesId int,
. . .
);
create table personPhones (
personPhonesId int auto_increment primary key,
personId int,
. . .
foreign key (personId) references persons (personId),
unique (personId, personPhonesId) -- seems redundant but needed
);
alter table persons
add foreign key (personId, primary_personPhonesId) on personPhones(personId, personPhonesId);
It is tempting to declare primary_personPhonesId as not null. However, that makes it difficult to insert rows into the two tables.
An alternative method uses computed columns:
create table persons (
personId int auto_increment primary key,
. . .
);
create table personPhones (
personPhonesId int auto_increment primary key,
personId int,
isPrimary boolean,
. . .
foreign key (personId) references persons (personId),
primaryId as (case when isPrimary then personPhonesId end),
unique(primaryId)
);
Similar to the previous solution, this does not guarantee that isPrimary is always set.
You can try the below mentioned design:
Person (Id (PK),name,....)
TelephoneNumber (Id(PK), telNo, PersonId(FK))
PrimaryTelNo (PersonId(FK), TelId(FK))
You can create a table showing mapping of TelId and PersonId and declare the combination of TelId and PersonId as composite primary key
The simplest way is to make the 'first' one primary, but this becomes tricky when you want to change which one is primary. In that case, I believe you can do this...
CREATE TABLE my_table
(person_id INT NOT NULL
,phone VARCHAR(12) not null
,is_primary enum('1') null
,primary key(person_id,phone)
, unique (person_id,is_primary)
);
INSERT INTO my_table VALUES
(1,'123',1),
(1,'234',null),
(1,'345',null),
(2,'456',null),
(2,'567',1),
(2,'678',null);
So, the enum allows values of 1 and null, but while there can be several nulls, there can only be one '1' per person. However, this solution doesn't preclude the possibility that none of the numbers are primary!
You should create a third table person_primary_number with only two fields:
person_id
phone_number_id
In this table you should insert the ids of the person and his primary number. The primary key of this table is on these two columns.
Another way is to add primary_number_id directly to the person table. This is probably the simplest solution.
Then you should have:
person
—————-
id (primary key int autoincrement)
primary_number_id (foreign key for phone_number.id)
name
...
phone_number
———————————-
id (primary key int autoincrement)
person_id (foreign key for person.id)
phone_number
The only problem with this solution is that you can assign as primary phone the number of somebody else.
This violates a strong principle of schema design -- don't pack a list into a cell. But...
If you only need to display the phone number to some human who will be doing a call, and
If that human possibly needs to see non-primary numbers, then
Consider having a VARCHAR(100) column that has a commalist that starts with the 'primary' phone number and continues with alternative numbers.
Note that the application would be responsible for putting the list together, and dealing with updates. Or you could push this back onto the user by providing a UI that asks for "phone number(s), starting with the preferred one to call you with; please separate with commas."

Auto increment with composite primary key

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 );