mysql unique Will the order of insertion change? - mysql

mysql unique Will the order of insertion change?
create table class(
cid int primary key auto_increment,
caption varchar(10)
);
insert class(caption) values
("三年二班"),
("一年三班"),
("三年一班");
create table class1(
cid int primary key auto_increment,
caption char(10) unique
);
insert into class1(caption) values
('三年二班'),
('一年三班'),
('三年一班');

Related

AutoIncrementing Foreign Key?

I have a table A which has an Auto incrementing Primary key.
I have a table B with a field as foreign key referencing to those Primary key values.
I want to add a record in Table A and Table B simultaneously,(note I'm not defining these auto incrementing fields.When I execute my codes the records in table A are created but table B fails to do so. I understand that I cannot reference a foreign key as a auto incrementing null value but is there any alternative to what I'm trying to achieve???
My code for creating tables are:
Table A
Create TABLE IF NOT EXISTS Friends(
friend_id Int PRIMARY KEY AUTO_INCREMENT,
friend_email Varchar(50) NOT NULL UNIQUE,
Password Varchar(20) NOT NULL,
Profile_Name Varchar(30) NOT NULL,
Date_Started DATE NOT NULL,
Num_Of_Friends INT UNSIGNED )
Table B
Create TABLE IF NOT EXISTS myFriends(
friend_id1 Int AUTO_INCREMENT ,
friend_id2 Int NOT NULL,
FOREIGN KEY(friend_id1) REFERENCES Friends(friend_id))
The queries for adding into these tables
For adding into Table A
INSERT INTO `Friends` (`friend_id`, `friend_email`, `Password`, `Profile_Name`, `Date_Started`, `Num_Of_Friends`) VALUES (NULL, '$Email', '$password1', '$Profile_Name', CURRENT_DATE(), '0')";
For adding into Table B
INSERT INTO `myFriends` (`friend_id1`,`friend_id2`) VALUES (NULL,0)";

Foregin keys returns empty results

I'm using an a mySQL db on localhosts. Created table with primary key and another table with foreign key pointing to that one, but when I want to see the results all I geted is "alert" that MySQL returned emty result. Here my tables
CREATE TABLE example_1(
ex1_id int NOT NULL AUTO_INCREMENT,
first_name varchar(50) NULL,
last_name varchar(50) NULL,
CONSTRAINT example_1_pk PRIMARY KEY (ex1_id)
);
CREATE TABLE example_2 (
ex2_id int NOT NULL AUTO_INCREMENT,
acces_lvl int NOT NULL,
CONSTRAINT example_2_pk PRIMARY KEY (ex2_id)
);
CREATE TABLE example_3 (
ex3_id int NOT NULL AUTO_INCREMENT,
first int NOT NULL,
second int NOT NULL,
CONSTRAINT example_3_pk PRIMARY KEY (ex3_id),
FOREIGN KEY (first) REFERENCES example_1(ex1_id),
FOREIGN KEY (second) REFERENCES example_2(ex2_id)
);
Then I add something to db, eg.
INSERT INTO `example_1`(`first_name`, `last_name`) VALUES ('foo', 'bar');
and
INSERT INTO `example_2`(`acces_lvl`) VALUES (2)
then when I try
SELECT * FROM `example_3`
I have nothing, empty results. Shouldn't be there id's from other tables? Am I doing something wrong, or I didn't do something? I'm totally noob in database.
Because you did not insert any data into example_3. Foreign key constraints don't propagate data, they just enforce the data relationship, so when you do insert data into example_3, the values you put in the columns with foreign key constraints have corresponding values in other table.

How can I do an insert into to a column when I have a foreign key in mysql

Hello guys I have some problems I have been trying to inser data to a column which have a foreign key in MSQL But I can't make it work. I would appreciate if somebody help me with this.
Category
(
idCategory int(20) auto_increment not null,
NameCategory varchar(40) not null,
PRIMARY KEY (idCategory)
);
SubCategory
(
idSubCategory int(10)not null primary key auto_increment ,
NameSub varchar(40) not null,
FK_Category int not null
);
ALTER TABLE SubCategory auto_increment=1;
ALTER TABLE SubCategory
ADD FOREIGN KEY (PK_Category)
REFERENCES Category (idCategory);
I have tried this 3 ways but nothing works
INSERT INTO Subcategory (NameSub)
VALUES ( 'Nisan');
INSERT INTO Subcategory (idSubCategory, NameSub,PK_Category)
VALUES (01, 'Nisan', 01);
INSERT INTO subcategory (NameSub, PK_Category) VALUES
( 'Nisan' SELECT idCategory from Category WHERE idCategory = 1 );
For some reason your Foreign key constrains script didn't work for me so I did it another an alternate way.
I worked out why afterwards, you reference you have ADD FOREIGN KEY (PK_Category) rather than (FK_Category)
CREATE TABLE Category
(
idCategory int(20) auto_increment not null,
NameCategory varchar(40) not null,
PRIMARY KEY (idCategory)
);
CREATE TABLE SubCategory
(
idSubCategory int(10)not null primary key auto_increment ,
NameSub varchar(40) not null,
FK_Category int not null,
INDEX IDX_Category(FK_Category),
FOREIGN KEY (FK_Category)
REFERENCES Category(idCategory)
ON DELETE CASCADE
);
ALTER TABLE SubCategory auto_increment=1;
And here are the inserts
INSERT INTO Category (NameCategory)
VALUES ('Car');
INSERT INTO Subcategory (NameSub,FK_Category)
VALUES ('Nisan', 01);
As you didn't specify the contents of the table of Category I've created one.
Note: The issue you may be having is that your parent table is empty, and then it would error.
SQL Fiddle

Allow a foreign key insertion only if another foreign key is matched

I have these 3 tables:
--company--
company_id (primary key)
name
--location--
location_id (primary key)
company_id (foreign key referencing company.company_id)
name
--asset--
asset_id (primary_key)
company_id (foreign key referencing company.company_id)
location_id (foreign key referencing location.location_id)
name
I would like to enforce this: a location_id for an asset is acceptable only if asset.company_id = location.company_id
currently I'm enforcing this through the application, I was wondering if it's possible to do this using only MySQL.
drop table company;
create table company
( company_id int not null auto_increment,
name varchar(100) not null,
primary key(company_id)
)ENGINE=InnoDB
;
insert into company(name) values ('acme widgets');
insert into company(name) values ('goober chocolates');
insert into company(name) values ('Fat R Us');
drop table location;
create table location
( location_id int not null,
company_id int not null,
name varchar(100) not null,
primary key(company_id,location_id),
FOREIGN KEY (company_id ) REFERENCES company(company_id)
)ENGINE=InnoDB
;
insert into location(location_id,company_id,name) values (1,1,'Cambridge MA');
insert into location(location_id,company_id,name) values (1,2,'Boston MA');
insert into location(location_id,company_id,name) values (1,3,'Topeka KS');
insert into location(location_id,company_id,name) values (2,1,'Everywhere USA');
insert into location(location_id,company_id,name) values (2,666,'Fail Test this will fail');
create table asset
( asset_id int not null auto_increment,
company_id int not null,
location_id int not null,
name varchar(100) not null,
primary key(asset_id),
CONSTRAINT fk_asset_cl FOREIGN KEY (company_id,location_id)
REFERENCES location(company_id,location_id)
)ENGINE=InnoDB
;
insert into asset(company_id,location_id,name) values (1,1,'typewriter');
insert into asset(company_id,location_id,name) values (1,8,'typewriter fail');
remember that your FK must be back to a single parent table with a key in the same composite order (company,location) in this example
insert into asset(company_id,location_id,name) values (1,8,'typewriter fail');
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ...

In MySQL how does one create global/general foreign IDs?

Question:
Is there a way to make the foreign ID point to something more generic than one specific table?
Details:
Often I run into the situation where I have several tables which have nothing to do with each other, but still need a common table (in below examples engine is innodb)
CREATE TABLE IF NOT EXISTS movies
(
id INT NOT NULL auto_increment,
name VARCHAR(100) NOT NULL ,
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS books
(
id INT NOT NULL auto_increment,
name VARCHAR(100) NOT NULL ,
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS songs
(
id INT NOT NULL auto_increment,
name VARCHAR(100) NOT NULL ,
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS news_papers
(
id INT NOT NULL auto_increment,
name VARCHAR(100) NOT NULL ,
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS scrolls
(
id INT NOT NULL auto_increment,
name VARCHAR(100) NOT NULL ,
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS sumarian_wheat_tablets
(
id INT NOT NULL auto_increment,
name VARCHAR(100) NOT NULL ,
PRIMARY KEY(id)
);
Now I want to keep a record of every time each is viewed like so
CREATE TABLE IF NOT EXISTS movie_history
(
id INT NOT NULL auto_increment,
foreign_id INT NOT NULL ,
view_date TIMESTAMP DEFAULT now(),
FOREIGN KEY (foreign_id) REFERENCES movies ( id ),
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS book_history
(
id INT NOT NULL auto_increment,
foreign_id INT NOT NULL ,
view_date TIMESTAMP DEFAULT now(),
FOREIGN KEY (foreign_id) REFERENCES books ( id ),
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS song_history
(
id INT NOT NULL auto_increment,
foreign_id INT NOT NULL ,
view_date TIMESTAMP DEFAULT now(),
FOREIGN KEY (foreign_id) REFERENCES songs ( id ),
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS news_paper_history
(
id INT NOT NULL auto_increment,
foreign_id INT NOT NULL ,
view_date TIMESTAMP DEFAULT now(),
FOREIGN KEY (foreign_id) REFERENCES news_papers ( id ),
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS scroll_history
(
id INT NOT NULL auto_increment,
foreign_id INT NOT NULL ,
view_date TIMESTAMP DEFAULT now(),
FOREIGN KEY (foreign_id) REFERENCES scrolls ( id ),
PRIMARY KEY(id)
);
CREATE TABLE IF NOT EXISTS sumarian_wheat_tablet_history
(
id INT NOT NULL auto_increment,
foreign_id INT NOT NULL ,
view_date TIMESTAMP DEFAULT now(),
FOREIGN KEY (foreign_id) REFERENCES sumarian_wheat_tablets ( id ),
PRIMARY KEY(id)
);
Is there a more correct way to handle such situations without making n new tables? I realize that I can make one history table and copy it over with CREATE TABLE...LIKE... but that still requires making n new tables, plus I have to go in and ALTER the foreign_id.
My first thought is just dump the fk reference and have one history table:
CREATE TABLE history(
base_table VARCHAR,
base_table_id INT,
view_date TIMESTAMP DEFAULT now()
);
But I assume you want the fk to maintain the integrity (question: is this really necessary, or can this be worked around?). I guess you could accomplish this by creating a table of "pks in use". For example:
create a table "keys" with columns id (autoincrement) and base_table_name
create a table "movies", where id is both pk and also a fk to "keys.id" (but not an autoincrement column)
add a "before insert" trigger to "movies" which inserts a record into "keys" returning the generated id to be used as the id for the "movie" record
create a history table with a fk to "keys"
create a "delete" trigger on "movies" which also removes the record from "keys" if you want the integrity maintained, or cascading deletes, etc
So the generated "id" is shared across many tables. There is a school of thought that suggests using a primary key unique across all relations within the database (an "enterprise key"), so it is not unprecedented. Instead of using sequences or autogenerated columns, sometimes a GUID or UUID is used.
This replaces extra history tables with triggers on each base table, which might not be a great thing, depending on your environment. I haven't done this myself, just throwing some thoughts out there, so take it for what its worth.
This depends on the record that you're keeping. If you just want to know hits, add one field to each table that is incremented each time your 'hit' criteria is met (ie, there is a read from a webpage). If you want to hold more information:
CREATE TABLE IF NOT EXISTS view_history
(
id INT NOT NULL,
table VARCHAR NOT NULL,
//other relevant stats to a given view, such as ip and so on.
)
The id and table form a composite key as to what table it refers to.
I don't think there is a way to specify more than one table on a single foreign key.
If you define a single history table, you cannot enforce referential integrity using a single foreign key. You could enforce it programmaticaly as explained here
This describes how to do it for other storage engines that do not support FKs, but could be used as a guide to implement what you need. It suggests creating triggers that will enforce same validations a foreign key would.
Other approach:
CREATE TABLE IF NOT EXISTS history
(
id INT NOT NULL auto_increment,
movie_id INT,
book_id INT,
song_id INT,
news_paper_id INT,
view_date TIMESTAMP DEFAULT now(),
FOREIGN KEY (movie_id) REFERENCES movie ( id ),
FOREIGN KEY (book_id) REFERENCES book ( id ),
FOREIGN KEY (song_id) REFERENCES song ( id ),
FOREIGN KEY (news_paper_id) REFERENCES news_paper ( id ),
PRIMARY KEY(id)
);