How to create relationships in MySQL - mysql

In class, we are all 'studying' databases, and everyone is using Access. Bored with this, I am trying to do what the rest of the class is doing, but with raw SQL commands with MySQL instead of using Access.
I have managed to create databases and tables, but now how do I make a relationship between two tables?
If I have my two tables like this:
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id )
)
and
CREATE TABLE customers(
customer_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
address VARCHAR(20) NOT NULL,
city VARCHAR(20) NOT NULL,
state VARCHAR(20) NOT NULL,
PRIMARY KEY ( customer_id )
)
How do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer_id (to indicate who owns it).

If the tables are innodb you can create it like this:
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id ),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;
You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look here for more info.

as ehogue said, put this in your CREATE TABLE
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
alternatively, if you already have the table created, use an ALTER TABLE command:
ALTER TABLE `accounts`
ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;
One good way to start learning these commands is using the MySQL GUI Tools, which give you a more "visual" interface for working with your database. The real benefit to that (over Access's method), is that after designing your table via the GUI, it shows you the SQL it's going to run, and hence you can learn from that.

CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id )
)
and
CREATE TABLE customers(
customer_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
address VARCHAR(20) NOT NULL,
city VARCHAR(20) NOT NULL,
state VARCHAR(20) NOT NULL,
)
How do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer_id (to indicate who owns it).
You have to ask yourself is this a 1 to 1 relationship or a 1 out of many relationship. That is, does every account have a customer and every customer have an account. Or will there be customers without accounts. Your question implies the latter.
If you want to have a strict 1 to 1 relationship, just merge the two tables.
CREATE TABLE customers(
customer_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
address VARCHAR(20) NOT NULL,
city VARCHAR(20) NOT NULL,
state VARCHAR(20) NOT NULL,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
)
In the other case, the correct way to create a relationship between two tables is to create a relationship table.
CREATE TABLE customersaccounts(
customer_id INT NOT NULL,
account_id INT NOT NULL,
PRIMARY KEY (customer_id, account_id),
FOREIGN KEY customer_id references customers (customer_id) on delete cascade,
FOREIGN KEY account_id references accounts (account_id) on delete cascade
}
Then if you have a customer_id and want the account info, you join on customersaccounts and accounts:
SELECT a.*
FROM customersaccounts ca
INNER JOIN accounts a ca.account_id=a.account_id
AND ca.customer_id=mycustomerid;
Because of indexing this will be blindingly quick.
You could also create a VIEW which gives you the effect of the combined customersaccounts table while keeping them separate
CREATE VIEW customeraccounts AS
SELECT a.*, c.* FROM customersaccounts ca
INNER JOIN accounts a ON ca.account_id=a.account_id
INNER JOIN customers c ON ca.customer_id=c.customer_id;

Adding onto the comment by ehogue, you should make the size of the keys on both tables match. Rather than
customer_id INT( 4 ) NOT NULL ,
make it
customer_id INT( 10 ) NOT NULL ,
and make sure your int column in the customers table is int(10) also.

Certain MySQL engines support foreign keys. For example, InnoDB can establish constraints based on foreign keys. If you try to delete an entry in one table that has dependents in another, the delete will fail.
If you are using a table type in MySQL, such as MyISAM, that doesn't support foreign keys, you don't link the tables anywhere except your diagrams and queries.
For example, in a query you link two tables in a select statement with a join:
SELECT a, b from table1 LEFT JOIN table2 USING (common_field);

Here are a couple of resources that will help get started: http://www.anchor.com.au/hosting/support/CreatingAQuickMySQLRelationalDatabase and http://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561
Also as others said, use a GUI - try downloading and installing Xampp (or Wamp) which run server-software (Apache and mySQL) on your computer.
Then when you navigate to //localhost in a browser, select PHPMyAdmin to start working with a mySQL database visually. As mentioned above, used innoDB to allow you to make relationships as you requested. Makes it heaps easier to see what you're doing with the database tables. Just remember to STOP Apache and mySQL services when finished - these can open up ports which can expose you to hacking/malicious threats.

One of the rules you have to know is that the table column you want to reference to has to be with the same data type as
The referencing table . 2 if you decide to use mysql you have to use InnoDB Engine because according to your question that’s the engine which supports what you want to achieve in mysql .
Bellow is the code try it though the first people to answer this question
they 100% provided great answers and please consider them all .
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY (account_id)
)ENGINE=InnoDB;
CREATE TABLE customers(
customer_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
address VARCHAR(20) NOT NULL,
city VARCHAR(20) NOT NULL,
state VARCHAR(20) NOT NULL,
PRIMARY KEY ( account_id ),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
)ENGINE=InnoDB;

create table departement(
dep_id int primary key auto_increment,
dep_name varchar(100) not null,
dep_descriptin text,
dep_photo varchar(100) not null,
dep_video varchar(300) not null
);
create table newsfeeds(
news_id int primary key auto_increment,
news_title varchar(200) not null,
news_description text,
news_photo varchar(300) ,
news_date varchar(30) not null,
news_video varchar(300),
news_comment varchar(200),
news_departement int foreign key(dep_id) references departement(dep_id)
);

Related

Didnt display results in database

I have a little problem with one database. I have already entered data in the individual tables in the database. The problem is that with this code, it displays the column names, but didnt return rows. I can't find the error. I think the problem is in JOIN itself. Any ideas for solving the problem?
SELECT cars.brand,
cars.model,
cars.yearofproduction,
cars.engine_type,
parts.part_name,
parts.price AS MONEY,
parts.quantity
FROM CATALOG
JOIN parts
ON parts.part_name = parts.id
JOIN cars
ON CATALOG.car_id = cars.id
WHERE quantity >= '0'
HAVING MONEY < (
SELECT AVG(price)
FROM cars
);
And here the tables. I've already insert values in the tables.
CREATE TABLE CATALOG.parts
(
id INT AUTO_INCREMENT PRIMARY KEY,
part_name VARCHAR(255) NOT NULL,
price DECIMAL NOT NULL,
DESCRIPTION VARCHAR(255) DEFAULT NULL,
quantity TINYINT DEFAULT 0
);
CREATE TABLE CATALOG.cars
(
id INT AUTO_INCREMENT PRIMARY KEY,
brand VARCHAR(255) NOT NULL,
model VARCHAR(255) NOT NULL,
yearofproduction YEAR NOT NULL,
engine_type SET('Diesel', 'A95', 'Gas', 'Metan')
);
CREATE TABLE CATALOG.catalog
(
part_id INT NOT NULL,
CONSTRAINT FOREIGN KEY(part_id) REFERENCES parts(id)
ON DELETE RESTRICT ON UPDATE CASCADE,
car_id INT NOT NULL,
CONSTRAINT FOREIGN KEY(car_id) REFERENCES cars(id)
ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY(part_id, car_id)
);

MYSQL Select One Row With Less

I'm making a database for a unit and I need a query that selects the vet with less appointments assigned so I can assign the next appointment to him or her. I don't know how to start, but I'm pretty sure I'll have to use variables here. Those are my tables:
CREATE TABLE IF NOT EXISTS staff (
stafId MEDIUMINT UNSIGNED AUTO_INCREMENT,
stafAdd VARCHAR(150) NOT NULL,
stafConNum VARCHAR(15) NOT NULL,
stafEma VARCHAR(40) NOT NULL,
stafFirNam VARCHAR(20) NOT NULL,
stafLasNam VARCHAR(30) NOT NULL,
stafPos ENUM('nurse', 'vet') NOT NULL,
PRIMARY KEY (stafId)
) engine = InnoDB;
CREATE TABLE IF NOT EXISTS vet (
vetId MEDIUMINT UNSIGNED AUTO_INCREMENT,
FOREIGN KEY (vetId) REFERENCES staff(stafId),
PRIMARY KEY (vetId)
) engine = InnoDB;
CREATE TABLE IF NOT EXISTS appointment (
appoId MEDIUMINT UNSIGNED AUTO_INCREMENT,
appoDat DATETIME NOT NULL,
appoPetId MEDIUMINT UNSIGNED,
FOREIGN KEY (appoPetId) REFERENCES pet(petId),
appoVetId MEDIUMINT UNSIGNED,
FOREIGN KEY (appoVetId) REFERENCES vet(vetId),
PRIMARY KEY (appoId)
) engine = InnoDB;
You should start by looking up the mysql MIN() function. Follow that up with learning about JOINs and you'll be breezing through this.
You could get the vet's with the number of appointment like this:
SELECT
*
FROM
(
SELECT
vet.vetId,
COUNT(*) AS nbrOfAppointment
FROM
vet
JOIN appointment
ON vet.vetId = appointment.appoVetId
) AS tbl
ORDER BY tbl.nbrOfAppointment ASC
This Request gives you the number of appointement per vet ordered by number of appointement.
Select vet.id, count(*) as nb_appointement
from vet
inner join appointement app on vet.vetId = app.appoVetId
group by vet.id
order by nb_appointement asc

two composite keys from same table

In a MySQL database, I need to create a new closure table (called closure_new) that integrates a two column foreign key to another table, concept. This means adding rows to closure_new that are not in closure. How do I set up the SQL to accomplish this?
Here is my first attempt at the code for populating closure_new:
INSERT INTO `closure_new`
SELECT o.subtypeId, d.id, d.effectiveTime
FROM concept d
JOIN closure o
ON o.subtypeId = d.id;
Note that my first attempt only addresses subtypeId/subtype_effectiveTime and might not address it completely. The SQL also needs to incorporate supertypeId/supertype_effectiveTime. How do I write the SQL to populate the closure_new table with records for each of the effectiveTime values associated with each subtypeId and each supertypeId?
Here is the concept table:
CREATE TABLE `concept` (
`id` BIGINT NOT NULL DEFAULT 0,
`effectiveTime` VARCHAR(8) NOT NULL DEFAULT '',
`some other fields`,
PRIMARY KEY (`id`,`effectiveTime`)
) ENGINE=InnoDB;
Here is the old closure table:
CREATE TABLE `closure` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`subtypeId` BIGINT(20) NOT NULL ,
`supertypeId` BIGINT(20) NOT NULL ,
PRIMARY KEY (`id`)
);
Here is the closure_new table that needs to be populated with the script I started to write above:
CREATE TABLE `closure_new` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`subtypeId` BIGINT(20) NOT NULL ,
`subtype_effectiveTime` VARCHAR(8) NOT NULL DEFAULT '',
`supertypeId` BIGINT(20) NOT NULL ,
`supertype_effectiveTime` VARCHAR(8) NOT NULL DEFAULT '',
FOREIGN KEY (`supertypeId`, `supertype_effectiveTime`) references concept(`id`, `effectiveTime`),
FOREIGN KEY (`subtypeId`, `subtype_effectiveTime`) references concept(`id`, `effectiveTime`)
); ENGINE=InnoDB;
Try this:
insert into closure_new
(subtypeId, subtype_effectiveTime, supertypeId, supertype_effectiveTime)
select cl.id, co.effectiveTime, co.id, co.effectiveTime from closure cl inner join concept co
Your data better match or you will have some foreign key constraint issues
Not sure if I completely understand what you're after, but how about:
INSERT INTO `closure_new` (subtypeId, subtype_effectiveTime, supertypeId, supertype_effectiveTime)
SELECT subCon.id, subCon.effectiveTime, superCon.id, superCOn.effectiveTimed.effectiveTime
FROM closure o, concept subCon, concept superCon
where subcon.Id = o.subtypeId and supercon.Id = o.supertypeId
Or possibly, you could just create view with that select statement.

MySQL UNIQUE key not working

I am building as type on inventory table that keeps track of stock by 6 different factors. I am using an I query much like this one:
INSERT INTO inventory ( productid, factor1, factor2, factor3, factor4, factor5, factor6, quantity, serial_number)
VALUES (242332,1,1,1,'V67',3.30,'NEW',10,NULL)
ON DUPLICATE KEY UPDATE `quantity` = VALUES(`quantity`) + quantity;
The inventory table has a UNIQUE KEY for ( productid, factor1, factor2, factor3, factor4, factor5, factor6, serial_number ). For some reason, it is not picking up on the key and just INSERTing instead of UPDATEing. Can anyone offer an explanation why? What am I missing?
Here is the table create statement:
CREATE TABLE `inventory` (
`stockid` int(11) unsigned NOT NULL AUTO_INCREMENT,
`productid` int(11) unsigned NOT NULL,
`factor1` int(11) unsigned NOT NULL,
`factor2` int(11) unsigned NOT NULL,
`factor3` int(11) unsigned NOT NULL,
`factor4` varchar(8) NOT NULL,
`factor5` decimal(10,2) NOT NULL,
`factor6` enum('A','B','C','D','NEW') NOT NULL,
`quantity` int(11) NOT NULL,
`stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`serial_number` varchar(11) DEFAULT NULL,
PRIMARY KEY (`stockid`),
UNIQUE KEY `serial_number` (`serial_number`),
UNIQUE KEY `productid_2` (`productid`,`factor1`,`factor2`,`factor3`,`factor4`,`factor5`,`factor6`,`serial_number`),
KEY `productid` (`productid`),
KEY `factor1` (`factor1`),
KEY `factor2` (`factor2`),
KEY `factor3` (`factor3`),
CONSTRAINT `books_stock_ibfk_2` FOREIGN KEY (`productid`) REFERENCES `produx_products` (`productid`),
CONSTRAINT `books_stock_ibfk_5` FOREIGN KEY (`factor1`) REFERENCES `table_factor1` (`factorid`),
CONSTRAINT `books_stock_ibfk_6` FOREIGN KEY (`factor2`) REFERENCES `table_factor2` (`factorid`),
CONSTRAINT `books_stock_ibfk_7` FOREIGN KEY (`factor3`) REFERENCES `table_factor3` (`factorid`)
)
ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=latin1
More in-depth:
The purpose of this table is to hold stock quantities. I think this is pretty straight forward. The factors that separate these quantities are as follows:
factor1 = storeid (the unique indentifier for the store that ownes this quantity).
factor2 = supplierid (the unique indentfier for the supplier that we got the quantity from)
factor3 = warehouseid (unique identifier for the warehouse where it resides)
factor4 = locationid (unique string for the location. Its physically painted on the shelf)
factor5 = cost (what we paid for each of the quantity)
factor6 = condition (enum ['NEW','USED','RENTAL','PREORDER']. The first three are easy, the fourth is for quantites we ordered, want to sell, but have not received it yet.)
I know this is a hefty key but I am forced to keep it this way. I have had many suggestion to move cost or condition to the product table. I cannot do this. The cost isn't always the same since we buy a lot from auctions or other places with very variable costs and conditions.
I hope this helps more to explain what I am trying to do.
Mysql allows multiple NULLs in an unique constraint.In your serial_number column replace NULL with a value and the constraint is triggered,see:
http://sqlfiddle.com/#!2/9dbd19/1
a UNIQUE index permits multiple NULL values for columns that can
contain NULL
Docs
Make the column NOT NULL and use '' which is empty.

SQL select entries in other table linked by foreign keys

I have redesigned my database structure to use PRIMARY and FOREIGN KEYs to link the entries in my 3 tables together, and I am having problems trying to write queries to select data in one table given data in a another table. Here is an example of my 3 CREATE TABLE statements:
CREATE TABLE IF NOT EXISTS players (
id INT(10) NOT NULL AUTO_INCREMENT,
username VARCHAR(16) NOT NULL,
uuid VARCHAR(200) NOT NULL DEFAULT 0,
joined TIMESTAMP DEFAULT 0,
last_seen TIMESTAMP DEFAULT 0,
PRIMARY KEY (id)
);
/* ^
One |
To
| One
v
*/
CREATE TABLE IF NOT EXISTS accounts (
id INT(10) NOT NULL AUTO_INCREMENT,
account_id INT(10) NOT NULL,
pass_hash VARCHAR(200) NOT NULL,
pass_salt VARCHAR(200) NOT NULL,
created BIGINT DEFAULT 0,
last_log_on BIGINT DEFAULT 0,
PRIMARY KEY (id),
FOREIGN KEY (account_id) REFERENCES players(id) ON DELETE CASCADE
) ENGINE=InnoDB;
/* ^
One |
To
| Many
v
*/
CREATE TABLE IF NOT EXISTS purchases (
id INT(10) NOT NULL AUTO_INCREMENT,
account_id INT(10) NOT NULL,
status VARCHAR(20) NOT NULL,
item INT NOT NULL,
price DOUBLE DEFAULT 0,
description VARCHAR(200) NOT NULL,
buyer_name VARCHAR(200) NOT NULL,
buyer_email VARCHAR(200) NOT NULL,
transaction_id VARCHAR(200) NOT NULL,
payment_type VARCHAR(20) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (account_id) REFERENCES accounts(account_id) ON DELETE CASCADE
) ENGINE=InnoDB;
Say for example, I want to select all the usernames of users who purchased anything greater than $30. All the usernames are stored in the players table, which is linked to the accounts table and that is linked to the purchases table. Is this this the best way to design this relational database? If so, how would I run queries similar to the above example?
I was able to get get all of a users purchase history given their username, but I did it with 2 sub-queries... Getting that data should be easier than that!
Here is the SELECT query I ran to get all of a players purchase data:
SELECT *
FROM purchases
WHERE account_id = (SELECT id FROM accounts WHERE account_id = (SELECT id FROM players WHERE username = 'username'));
Also, when I try to make references to the other tables using something like 'players.username', I get an error saying that the column doesn't exist...
I appreciate any help! Thanks!
Your design is ok in my opinion. The relation between players and account is one-to-many and not one-to-one since this way, you can have two tuples referencing a single player.
I would write the query you need as:
SELECT DISTINCT p.id, p.username
FROM players p INNER JOIN accounts a ON (p.id = a.account_id)
INNER JOIN purchases pc ON (a.id = pc.account_id)
WHERE (pc.price > 30);
As Sam suggested, I added DISTINCT to avoid repeating id and username in case a user have multiple purchases.
Note the id is here to avoid confusion among repeated usernames.