i was wondering how do i use the select query to Retrieve all offers of a listing.
Any tips or help to improve my codes is appreciated to! Thank you and have a nice day!
CREATE DATABASE IF NOT EXISTS `assignment_db`;
USE `assignment_db`;
CREATE TABLE USER_LIST(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userName VARCHAR(50) NOT NULL,
email varchar(100) NOT NULL,
registeredDate timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
create table listing_list(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
itemName VARCHAR(50) NOT NULL,
itemDescription VARCHAR(254) NOT NULL,
price DECIMAL(4,2) NOT NULL,
fk_poster_id int references USER_LIST(id),
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
create table offer_list(
id int(6) Unsigned auto_increment Primary key,
offer int,
fk_listing_id int references listing_list(id),
fk_offeror_id int references user_list(id),
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
insert into user_list (userName, email) values ('John','johnnyboi#123.com');
insert into user_list (userName, email) values ('Tom','Tommyboi#123.com');
insert into listing_list (itemName,itemDescription, price) values ( 'Pen', 'A long delicate pen.',' 1.50 ');
insert into listing_list (itemName,itemDescription, price) values ( 'Pencil', 'A long delicate pencil.',' 0.50 ');
insert into offer_list (offer,fk_listing_id,fk_offeror_id) values ('200','2','3');
insert into offer_list (offer,fk_listing_id,fk_offeror_id) values ('200','1','1');
All offer listing for existing user :
select a.*,b.*,c.* from offer_list a
INNER JOIN (listing_list as b)
on a.fk_listing_id=b.Id
INNER JOIN (user_list as c)
on a.fk_offeror_id=c.Id
just all offer listing :
select a.*,b.* from listing_list b
INNER JOIN (offer_list as a)
on a.fk_listing_id=b.Id
just all offer listing 2nd way
select a.*,b.* from offer_list a
INNER JOIN (listing_list as b)
on a.fk_listing_id=b.Id
Check it here , i tested them in this FIDDLE
Related
I created some tables but when I want to check if my data is inside it doesn't show anything when
I use select * from Project it just appears null and I don't have null values I'm not sure what I'm doing wrong it just appears that the foreign key is restrict
`create table Department
(
`did integer not null auto_increment,
Dname varchar(50) default 'HR',
location varchar(50) default 'Chicago',
primary key(did)`
);
`create table Employee`
(
Eid integer not null auto_increment,
DepartmentID integer default 5,
Ename varchar(50) default 'Josh',
Erank integer default 2,
Salary real default 5000.00,
primary key(Eid),
foreign key(DepartmentID) references Department(did)
);
/*drop table Project;*/
create table Project
(
Pid integer not null auto_increment,
DepartmentID integer default 5,
Pname varchar(50) default 'Sorting',
budget real default 5000.00,
StartYear integer default 2000,
primary key(Pid),
foreign key(DepartmentID) references Department(did)
);
insert
into Project(DepartmentID, Pname, budget, StartYear)
values(1, 'OS', 5000.00, 2018),
(2, 'Net', 6000.00, 2020);
select *
from Project;
Check this fiddle. There are no rows in Department, so the restraint keeps the insert into Projects from happening. Also, I removed the backticks:
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=64f8f0e9cccce2eb2ab77b37fcce54fd
Add COMMIT statements:
create table Project...
commit;
insert into Department values('HR','Chicago');
insert into Department values('Admin','New York');
insert into Project...
commit;
select * from Project;
create table product_details(
product_ID int primary key unique not null auto_increment,
product_name varchar(30) not null,
product_purchase_price int not null,
product_sale_price int not null
);
Insert into product_details( product_ID,product_name, product_purchase_price, product_sale_price)
values(1,"lays",20,30);
insert into product_details( product_name, product_purchase_price, product_sale_price)
values("Choclate",30,35);
insert into product_details( product_name, product_purchase_price, product_sale_price)
values("Coke",90,120);
select * from product_details;
select (product_sale_price) - (product_purchase_price) As PROFIT
from product_details
where product_id=1;
CREATE TABLE Person (#Superclass
PPS varchar(9) NOT NULL PRIMARY KEY,
fName varchar(20) NOT NULL,
lName varchar(20) NOT NULL,
DOB date NOT NULL,
gender enum('M','F') NOT NULL DEFAULT 'M',
email varchar(25) NOT NULL,
contactNo varchar(10) NOT NULL,
city varchar(10) NOT NULL,
street varchar(20) NOT NULL
);
CREATE TABLE Donor (#Subclass
PPS varchar(9) NOT NULL PRIMARY KEY REFERENCES Person(PPS),
timesOfDonations int(1) NOT NULL DEFAULT '0'
);
CREATE TABLE Doctor(#Subclass
PPS varchar(9) NOT NULL PRIMARY KEY REFERENCES Person(PPS),
speciality varchar(20) NOT NULL,
workHours int(3)
);
CREATE TABLE Health_Check (
hId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
bloodPressure varchar(7) NOT NULL,
weight float(4,1) NOT NULL,
height float(4,1) NOT NULL,
heartRate int(3) NOT NULL,
temprature float(3,1) NOT NULL,
alcoholicTest enum('P','F') NOT NULL DEFAULT 'P',
dateOfCheck date,
doctorId varchar(9),
donorId varchar(9)
);
ALTER TABLE Health_Check
ADD CONSTRAINT donorH_fk FOREIGN KEY (donorId) REFERENCES Donor (PPS) ON DELETE RESTRICT ON UPDATE CASCADE,
ADD CONSTRAINT doctor_fk FOREIGN KEY (doctorId) REFERENCES Doctor (PPS) ON DELETE RESTRICT ON UPDATE CASCADE;
#List the doctors and the names of the donors they examined during the last week.
CREATE VIEW DoctorsAndDonors AS
SELECT * FROM (SELECT concat(fname, ' ', lName) AS'Doctor Name' FROM Person JOIN Doctor on Person.PPS=Doctor.PPS
JOIN Health_Check on Doctor.PPS = Health_Check.doctorId WHERE DATEDIFF(CURDATE(), dateOfCheck) BETWEEN 1 AND 7
UNION ALL
SELECT concat(fname, ' ', lName) AS'Donor Name' FROM Person JOIN Donor on Person.PPS=Donor.PPS
JOIN Health_Check on Donor.PPS = Health_Check.donorId WHERE DATEDIFF(CURDATE(), dateOfCheck) BETWEEN 1 AND 7) AS a;
The above VIEW is returning correct result but the names of doctors and donors are in one column under the label "Doctor Name".
My question is:
Is there a way that I can create two separate columns one shows the name of the doctors and the second shows the name of donors.
Thanks.
You'll need to join all of your tables together to get from the PERSON record for the Doctor to the Person record for the Donor using your Health_Check table to determine the relationship. Probably something like:
SELECT
CONCAT (DoctorPerson.fname,' ',DoctorPerson.lName) AS 'Doctor Name',
CONCAT (DonorPerson.fname,' ',DonorPerson.lName) AS 'Donor Name'
FROM Person as DoctorPerson
INNER JOIN Doctor ON DoctorPerson.PPS = Doctor.PPS
INNER JOIN Health_Check ON Doctor.PPS = Health_Check.doctorId
INNER JOIN Donor ON health_check.donorid = donor.PPS
INNER JOIN Person as DonorPerson ON Donor.PPS = DonorPerson.PPS
WHERE DATEDIFF(CURDATE(), dateOfCheck) BETWEEN 1 AND 7
_
Hello everyone!
I have table
CREATE TABLE `labels` (
`id` INT NULL AUTO_INCREMENT DEFAULT NULL,
`name` VARCHAR(250) NULL DEFAULT NULL,
`score` INT NULL DEFAULT NULL,
`before_score` INT NULL DEFAULT NULL,
PRIMARY KEY (`id`)
);
And I Have This Table
CREATE TABLE `scores` (
`id` INT NULL AUTO_INCREMENT DEFAULT NULL,
`name_id` INT NULL DEFAULT NULL,
`score` INT NULL DEFAULT NULL,
`date` DATETIME DEFAULT NULL,
PRIMARY KEY (`id`)
);
And i want have result where labels.score - have value last scores.score sorted by scores.date and labels.before_score where have value penultimate scores.score sorted by scores.date. Can I do This Only on Mysql slq and how?
Thanks.
ADD
For example i have this data on first table:
INSERT INTO `labels` (id, name, score, before_score) VALUES (1, 'John', 200, 123);
INSERT INTO `labels` (id, name, score, before_score) VALUES (2, 'Eddie', 2000, 2000);
INSERT INTO `labels` (id, name, score, before_score) VALUES (3, 'Bob', 400, 3101);
And second table
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('1','1','12','2013-07-10');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('2','2','2000','2013-05-04');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('3','3','654','2012-09-12');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('4','1','123','2013-12-17');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('5','1','200','2014-04-25');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('6','3','3101','2013-12-02');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('6','2','2000','2015-12-02');
INSERT INTO `scores` (`id`,`name_id`,`score`,`date`) VALUES ('6','3','400','2013-12-02');
If I understand correctly, you need the last two scores for each name_id.
I would tackle this with temporary tables:
Step 1. Last score:
create temporary table temp_score1
select name_id, max(`date`) as lastDate
from scores
group by name_id;
-- Add the appropriate indexes
alter table temp_score1
add unique index idx_name_id(name_id),
add index idx_lastDate(lastDate);
Step 2. Penultimate score. The idea is exactly the same, but using temp_score1 to filter the data:
create temporary table temp_score2
select s.name_id, max(`date`) as penultimateDate
from scores as s
inner join temp_score1 as t on s.nameId = t.nameId
where s.`date` < t.lastDate
group by name_id;
-- Add the appropriate indexes
alter table temp_score2
add unique index idx_name_id(name_id),
add index idx_penultimateDate(penultimateDate);
Step 3. Put it all together.
select
l.id, l.name,
s1.lastScore, s2.penultimateScore
from
`labels` as l
left join temp_score1 as s1 on l.id = s1.name_id
left join temp_score2 as s2 on l.id = s2.name_id
You can put this three steps inside a stored procedure.
Hope this helps you.
Can a single column in a table can be referenced to multiple tables?
A very late answer, but for whoever is wondering & googeling.
YES this can be done, but it is NOT good practice and even though it is quite simple, it will probably blow up in your face if you're not very aware of what you are doing. Not recommended.
However, I can see uses. For instance, you have a large table of millions of records, and you want in exceptional cases link to unknown or multiple tables (in which case it better be many). With multiple tables, if you would make a foreign key for all of them, that would be a huge bloat in your database size. An unknown table would be possible for instance in a technical support system, where you want to link to record in a table where there might be a problem, and this could be (almost) all tables in the database, including future ones.
Of course you will need two fields to link with: a foreign key field and the name of the table it is linking to. Lets call them foreignId and linkedTable
linkedTable could be an enum or a string, preferrably enum (less space), but that's only possible if the different tables you want to link to, are fixed.
Let's give an extremely silly example. You have an enormous user table users of which some user can add exactly one personal set of data to their profile. This can be about a hobby, a pet, a sport they practice or their profession. Now this info is different in all four cases. (4 possible tables is in reality not enough to justify this structure)
Now let's say linkedTable is an enum with possible values pets, hobbies, sports and professions, which are the names of four differently structured tables. Let's say id is the pkey in all four of them.
You join for instance as follows:
SELECT * FROM users
LEFT JOIN pets ON linkedTable = 'pets' AND foreignId = pets.id
LEFT JOIN hobbies ON linkedTable = 'hobbies' AND foreignId = hobbies.id
LEFT JOIN sports ON linkedTable = 'sports' AND foreignId = sports.id
LEFT JOIN professions ON linkedTable = 'professions' AND foreignId = professions.id
This is just to give a basic jest. Since you probably only need the link in rare cases, you will more likely do the lookup in your programming language, like PHP, when you loop through the users (without join).
Want to try out? You can try it yourself with building this test database (make sure you use a test database):
CREATE TABLE IF NOT EXISTS `users` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(100) NOT NULL ,
`linkedTable` ENUM('pets','hobbies','sports','professions') NULL DEFAULT NULL ,
`foreignId` INT NULL DEFAULT NULL ,
PRIMARY KEY (`id`), INDEX (`linkedTable`)
) ;
CREATE TABLE IF NOT EXISTS `pets` (
`id` INT NOT NULL AUTO_INCREMENT ,
`animalTypeId` INT NOT NULL ,
`name` VARCHAR(100) NOT NULL ,
`colorId` INT NOT NULL ,
PRIMARY KEY (`id`), INDEX (`animalTypeId`), INDEX (`colorId`)
) ;
CREATE TABLE IF NOT EXISTS `hobbies` (
`id` INT NOT NULL AUTO_INCREMENT ,
`hobbyTypeId` INT NOT NULL ,
`hoursPerWeekSpend` INT NOT NULL ,
`websiteUrl` VARCHAR(300) NULL ,
PRIMARY KEY (`id`), INDEX (`hobbyTypeId`)
) ;
CREATE TABLE IF NOT EXISTS `sports` (
`id` INT NOT NULL AUTO_INCREMENT ,
`sportTypeId` INT NOT NULL ,
`hoursPerWeekSpend` INT NOT NULL ,
`nameClub` VARCHAR(100) NULL ,
`professional` TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (`id`), INDEX (`sportTypeId`)
) ;
CREATE TABLE IF NOT EXISTS `professions` (
`id` INT NOT NULL AUTO_INCREMENT ,
`professionId` INT NOT NULL ,
`hoursPerWeek` INT NOT NULL ,
`nameCompany` VARCHAR(100) NULL ,
`jobDescription` VARCHAR(400) NULL,
PRIMARY KEY (`id`), INDEX (`professionId`)
) ;
INSERT INTO `users` (`id`, `name`, `linkedTable`, `foreignId`)
VALUES
(NULL, 'Hank', 'pets', '1'),
(NULL, 'Peter', 'hobbies', '2'),
(NULL, 'Muhammed', 'professions', '1'),
(NULL, 'Clarice', NULL, NULL),
(NULL, 'Miryam', 'professions', '2'),
(NULL, 'Ming-Lee', 'hobbies', '1'),
(NULL, 'Drakan', NULL, NULL),
(NULL, 'Gertrude', 'sports', '2'),
(NULL, 'Mbase', NULL, NULL);
INSERT INTO `pets` (`id`, `animalTypeId`, `name`, `colorId`)
VALUES (NULL, '1', 'Mimi', '3'), (NULL, '2', 'Tiger', '8');
INSERT INTO `hobbies` (`id`, `hobbyTypeId`, `hoursPerWeekSpend`, `websiteUrl`)
VALUES (NULL, '123', '21', NULL), (NULL, '2', '1', 'http://www.freesoup.org');
INSERT INTO `sports` (`id`, `sportTypeId`, `hoursPerWeekSpend`, `nameClub`, `professional`)
VALUES (NULL, '2', '3', 'Racket to Racket', '0'), (NULL, '12', '34', NULL, '1');
INSERT INTO `professions` (`id`, `professionId`, `hoursPerWeek`, `nameCompany`, `jobDescription`)
VALUES (NULL, '275', '40', 'Ben & Jerry\'s', 'Ice cream designer'), (NULL, '21', '24', 'City of Dublin', 'Garbage collector');
Then run the first query.
Fun note for discussion: How would you index this?
If you mean "can a column in one table be used as a foreign key in multiple tables", then the answer is YES. This is the whole point of a relational database
Yes, you can do that so. here is a sample on how to do it:
Here is the table that has a column(CountryID) that will be referenced by multiple tables:
CREATE TABLE DLAccountingSystem.tblCountry
(
CountryID INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
CountryName VARCHAR(128) NOT NULL,
LastEditUser VARCHAR(128) NOT NULL,
LastEditDate DATETIME NOT NULL
) ENGINE=INNODB;
Here are the tables that is going to reference the column(CountryID):
CREATE TABLE DLAccountingSystem.tblCity
(
CityID INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
CountryID INT NOT NULL,
CityName VARCHAR(128) NOT NULL,
LastEditUser VARCHAR(128) NOT NULL,
LastEditDate DATETIME NOT NULL
) ENGINE=INNODB;
CREATE TABLE DLAccountingSystem.tblProvince
(
ProvinceID INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
CountryID INT NOT NULL,
ProvinceName VARCHAR(128) NOT NULL,
LastEditUser VARCHAR(128) NOT NULL,
LastEditDate DATETIME NOT NULL
) ENGINE=INNODB;
Here is how you create a reference to the column:
ALTER TABLE DLAccountingSystem.tblCity
ADD CONSTRAINT fk_tblcitycountryid FOREIGN KEY CountryID (CountryID)
REFERENCES DLAccountingSystem.tblCountry (CountryID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
ALTER TABLE DLAccountingSystem.tblProvince
ADD CONSTRAINT fk_tblprovincecountryid FOREIGN KEY CountryID (CountryID)
REFERENCES DLAccountingSystem.tblCountry (CountryID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
here is a table that has column that references different columns from (CountryID, ProvinceID, CityID) multiple tables(I Don't personally advice this way of table structuring. Just my opinion no offense ;) )
CREATE TABLE DLAccountingSystem.tblPersons
(
PersonID INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
PlaceID INT NOT NULL,
PlaceTypeID INT NOT NULL, -- this property refers to what table are you referencing.
//Other properties here.....
) ENGINE=INNODB;
you should also have a lookup table that would contain the PlaceType:
CREATE TABLE DLAccountingSystem.tblPlaceType
(
PlaceTypeID INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
PlaceTypeName INT NOT NULL
//Other properties here.....
) ENGINE=INNODB;
here is how you fetch it:
SELECT p1.PersonID,
tcity.CityName,
tprov.ProvinceName,
tcoun.CountryName
FROM DLAccountingSystem.tblPersons p1
LEFT JOIN (SELECT p2.PersonID, p2.PlaceTypeID, c.CityName FROM DLAccountingSystem.tblPersons p2 INNER JOIN DLAccountingSystem.tblCity c ON p2.ObjectID = c.CityID WHERE PlaceTypeID = #CityTypeID) tcity ON p1.PersonID = tcity.PersonID
LEFT JOIN (SELECT p2.PersonID, p2.PlaceTypeID, c.ProvinceName FROM DLAccountingSystem.tblPersons p2 INNER JOIN DLAccountingSystem.tblProvince c ON p2.ObjectID = c.ProvinceID WHERE PlaceTypeID = #ProvinceTypeID) tprov ON p1.PersonID = tprov.PersonID
LEFT JOIN (SELECT p2.PersonID, p2.PlaceTypeID, c.CountryName FROM DLAccountingSystem.tblPersons p2 INNER JOIN DLAccountingSystem.tblCountry c ON p2.ObjectID = c.CountryID WHERE PlaceTypeID = #CountryTypeID) tcoun ON p1.PersonID = tcoun.PersonID
you can select from other tables like
A same column or set of columns can act as a parent and/or as a child endpoint of a foreign key or foreign keys.