SQL query to get record from tables - mysql

I have a small query to be answered.
There are 4 tables call it as
user : uid, uname
category: cid,canme
product : pid, pname
assemble : aid, uid,pid,cid;
I want to display a record from product table but the requirement is pid(from product) and uid (from user) should not be present in assemble table in the same row at a time.

I believe this is what you're looking for:
select * from user u, product p, assemble a where p.pid not in
(Select pid from assemble) and u.uid not in (select uid from assemble)

Check out this SQL Fiddle and the comments within. You're covering a lot of concepts here, and you'll want to think about your design and what you're trying to accomplish, but to address the goals you've set forth in your question:
You can use PRIMARY KEYS or UNIQUE CONSTRAINTS to ensure that duplicate values don't get inserted into your tables (e.g., you don't want pid and cid to be duplicated in the assemble table, so I made that the primary key). I'm being very literal with your statement:
the requirement is pid(from product) and uid (from user) should not be present in assemble table in the same row at a time. (emphasis mine)
You can use JOINS to relate items from different tables to one another. In fact, your assemble table is often referred to as a "join table". My example is using inner joins (meaning, values must exist in both tables).
You can use FOREIGN KEYS to ensure that columns you want to reference in another table exist there.
Below is the code in case SQL Fiddle misbehaves.
Create and populate the tables:
CREATE TABLE users (
uid serial,
uname text,
CONSTRAINT user_pkey PRIMARY KEY (uid)
);
CREATE TABLE categories (
cid serial,
cname text,
CONSTRAINT cat_pkey PRIMARY KEY (cid)
);
CREATE TABLE products (
pid serial,
pname text,
CONSTRAINT prod_pkey PRIMARY KEY (pid)
);
CREATE TABLE assemble (
join_id serial,
uid bigint,
pid bigint,
cid bigint,
CONSTRAINT assemble_pkey PRIMARY KEY (uid, pid),
CONSTRAINT assemble_user_fkey FOREIGN KEY (uid)
REFERENCES users (uid),
CONSTRAINT assemble_prod_fkey FOREIGN KEY (pid)
REFERENCES products (pid),
CONSTRAINT assemble_cat_fkey FOREIGN KEY (cid)
REFERENCES categories (cid)
);
INSERT INTO users (uname) VALUES ('Akshay');
INSERT INTO users (uname) VALUES ('Mom');
INSERT INTO users (uname) VALUES ('Dad');
INSERT INTO categories (cname) VALUES ('Shoes');
INSERT INTO categories (cname) VALUES ('Hats');
INSERT INTO categories (cname) VALUES ('Coats');
INSERT INTO products (pname) VALUES ('Blue Suede Nikes');
INSERT INTO products (pname) VALUES ('Fedora');
INSERT INTO products (pname) VALUES ('Flying Jacket');
-- Give Akshay a hat
INSERT INTO assemble (uid, cid, pid)
VALUES (
(SELECT uid FROM users WHERE uname='Akshay'),
(SELECT cid FROM categories WHERE cname='Hats'),
(SELECT pid FROM products WHERE pname='Fedora')
);
-- Give Mom a coat
INSERT INTO assemble (uid, cid, pid)
VALUES (
(SELECT uid FROM users WHERE uname='Mom'),
(SELECT cid FROM categories WHERE cname='Coats'),
(SELECT pid FROM products WHERE pname='Flying Jacket')
);
-- Give Dad some shoes
INSERT INTO assemble (uid, cid, pid)
VALUES (
(SELECT uid FROM users WHERE uname='Dad'),
(SELECT cid FROM categories WHERE cname='Shoes'),
(SELECT pid FROM products WHERE pname='Blue Suede Nikes')
);
Queries:
-- get the data out of your assemble table, with names from related tables
SELECT u.uname, c.cname, p.pname
FROM users u
INNER JOIN assemble j
ON u.uid = j.uid
INNER JOIN categories c
ON j.cid = c.cid
INNER JOIN products p
ON p.pid = j.pid;
-- Give Mom the same coat... this will fail due to the PRIMARY KEY, even with a different category
INSERT INTO assemble (uid, cid, pid)
VALUES (
(SELECT uid FROM users WHERE uname='Mom'),
(SELECT cid FROM categories WHERE cname='Hats'),
(SELECT pid FROM products WHERE pname='Flying Jacket')
);

Related

MySQL: how to insert into a table with two foreign keys linking to two other tables?

I have the following db structure with 3 tables as an example:
Employee
id // primary key, autoincrement
employee_no // a varchar
Scenario
id // primary key, autoincrement
key // a varchar
Case
id // primary key, auto-increment
employee_id // foreign key to Employee table
scenario_id // foreign key to Scenario table
Say I already have data in employee and scenario table and I want to insert a new case into the case table so that it fills the foreign keys during the insert. The new case has employee_no in employee table and key in scenario table. I will need to join the two tables using the above values to get employee id and scenario id.
This post (Mysql: How to insert values in a table which has a foreign key) showed how this can be done with one foreign key, how do I do the same thing with two foreign keys?
I currently have something like this that does not work:
INSERT INTO `case` (scenario_id, employee_id, employee_no)
SELECT
(SELECT scenario.id FROM scenario WHERE scenario.`key` = 'UC01') as scenario_id,
(SELECT employee.id, employee.employee_no FROM employee WHERE employee.employee_no = "0001") as employee_id, employee_no
Join the two tables:
INSERT INTO case (scenario_id, employee_id)
SELECT s.id, e.id
FROM scenario AS s
CROSS JOIN emplopyee AS e
WHERE s.`key` = 'UC01'
AND e.employee_no = '0001'

How to fetch details and how to connect category and book table structure ( how to use GROUP_CONCAT)

My Problem is
I have table named category with id and category-name
and book with id and book-name
Please write SQL query for fetch result, result should be like
book1- c1,c2,c3
book2- c2,c3
book3-c4
etc.
You need to create an additional table:
CREATE TABLE book_categories (
book_id INT,
category_id INT,
PRIMARY KEY (book_id, category_id),
FOREIGN KEY book_id REFERENCES book (id),
FOREIGN KEY category_id REFERENCES category (id)
)
Then you can use a JOIN to get your result:
SELECT book_name, GROUP_CONCAT(category_name)
FROM book AS b
JOIN book_categories AS bc ON bc.book_id = b.id
JOIN categoriy AS c ON c.id = bc.category_id
GROUP BY b.id

mysql - call to insert into another table on every value of select

I'm currently migrating data from our old database schema into a new one.
I have a table called Product on my old database, on my new database schema I still have a Product table and a new column for b_id, and another table B.
During migration, I will need to insert an entry to table B for every product that I have in my table and update the Product table to set the b_id for the newly created entry on b for this product. How can I accomplish this?
To transfer the data for the product table, I have:
INSERT INTO newSchema.Product
SELECT id, prodName
FROM oldSchema.Product
I'm thinking of looping into the oldSchema.Product and for every product, have a call to INSERT INTO B and UPDATE TABLE Product, but no idea how to put this into code.
Any help will be appreciated. Thanks!
The same goes for B table...
INSERT INTO newschema.B (product_id)
SELECT id
FROM oldschema.product
Edited:
CREATE TABLE newschema.b (
id INT NOT NULL AUTO_INCREMENT,
product_id INT,
PRIMARY KEY (id)
);
CREATE TABLE newschema.product (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(35) NOT NULL,
b_id INT,
PRIMARY KEY (id),
FOREIGN KEY (b_id) REFERENCES b(id)
);
INSERT INTO newschema.b (product_id)
SELECT product_id
FROM oldschema.product ;
INSERT INTO newschema.product (id, name, b_id)
SELECT OP.id,
OP.name,
NB.id
FROM oldschema.product AS OP,
newschema.b AS NB
WHERE NB.product_id = OP.id ;

Why don't I get any output from my relation table?

I have created 'students' table where 'sid' is the primary key and I have inserted many values into sid. I have created a second table called 'courses' and it has a primary key 'cid' I have entered values for cid as well. Now, I want to create a relation table called 'enroll' which I have done like-
create table enroll(
grade char(2),
sid int not null,
cid int not null,
primary key(sid,cid),
foreign key (cid) references courses(cid) on delete cascade,
foreign key (sid) references students(sid) on delete cascade
);
Now, when I try to view the table using select * from enroll;
I don't get any output. It says "0 rows returned". Why is this? Isn't it supposed to have all the values of sid and cid from the other tables?
In Order to create a new table from values in your other table you can do something like this:
CREATE TABLE new_table AS (SELECT * FROM old_table);
The select statement will be the fields that will be pulled.
You can rename the columns like: Select [field name] as [what you want field name to be]
For More information read this article
Anyway for your particular case:
Create table enroll AS (Select s.sid AS 'Sid', c.cid AS 'Cid' from courses c inner join students s on c.something = s.something)
replace '.something' with the id of the student
you just created the table structure, the schema, your table is empty, so you dont get any results.

Mysql foreign key

I want to make a link between a table customer and a table product by an IdProduct.
Example:
Create table customer(
idcustomer INT not null,
name Varchar(20),
idproduct INT,
);
create table Product(
idproduct INT not null,
nameProduct varchar(40)
);
How can I link the two together like the foreign key system for, when I select a customer, I can get all his products? It's a question about the structure of the database.
You want to introduce a 3rd table to resolve the many-to-many relationship between customers and products. It should consist of idcustomer and idproduct.
Then, to get all the products for a given customer:
SELECT c.name, p.nameProduct
FROM Customer c
INNER JOIN CustomerProductXref cpx
ON c.idcustomer = cpx.idcustomer
INNER JOIN product p
ON cpx.idproduct = p.idproduct
WHERE c.idcustomer = 12345
In mysql a foreign key is a special type of constraint. It is preferably created with the table, but can also be added afterwards. In this case, you might define the constraint as:
ALTER TABLE customer
ADD FOREIGN KEY (idproduct)
REFERENCES Product (idproduct);
(Note that you have to use the InnoDB engine to take advantage of FK's in mysql. More here
However FK's aren't required to make a JOIN, which is how you would link the tables in a SELECT -
select c.idcustomer, c.name, p.nameproduct
from customer c
join Product p on p.idproduct=c.idproduct;
Here's how you'd make a foreign key constraint (ignoring the cardinality issues that Joe rightly suggests):
CREATE table Product(
idproduct INT not null,
nameProduct varchar(40),
PRIMARY KEY (idproduct )
);
CREATE table customer(
idcustomer INT not null,
name Varchar(20),
idproduct INT,
FOREIGN KEY (idproduct) REFERENCES Product(idproduct )
);
Get your data like this:
SELECT * FROM Product AS P
INNER JOIN Customer AS C ON C.idproduct = P.idproduct
WHERE C.idcustomer = 1