sql join on two fields in one table - mysql

i have bookings table which has two people- i want to return person_1 as a row, person_2 as a new row but with the person's id related to the people table
This is as far as i got-but doesnt pull in booking info
SELECT people.* FROM (
(select booking.person_1 as id from booking)
union ALL
(select booking.person_2 as id from booking)
) as peopleids
join people on people.id = peopleids.id;
heres my structure
CREATE TABLE IF NOT EXISTS `booking` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`slot` enum('morning_drive','afternoon_loop','return_drive') NOT NULL,
`type` enum('911','vintage_911') NOT NULL,
`car` int(11) NOT NULL,
`person_1` int(11) DEFAULT NULL,
`person_2` int(11) DEFAULT NULL,
`dated` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
CREATE TABLE IF NOT EXISTS `people` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`organisation` varchar(100) NOT NULL,
`event_date` date NOT NULL,
`wave` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
any ideas on how i could get a result set like- person.first_name, person.last_name, person.organisation, booking.dated, person.car, person.slot. im struggling with having two fields and having them to relate them into the one list
update for anyone interested in this and joining a 3rd table
heres my final query with php vars to pull in my certain dates and slots and also join a third table
SELECT peopleids.id,
peopleids.car,
cars.nr,
p.first_name,
p.last_name,
p.organisation,
p.event_date,
p.wave
FROM (SELECT booking.car, booking.person_1 as id FROM booking WHERE booking.dated = '".$date."' AND booking.`slot` = '".$slot."'
union ALL SELECT booking.car, booking.person_2 as id FROM booking WHERE booking.dated = '".$date."' AND booking.`slot` = '".$slot."'
) as peopleids
LEFT JOIN people p ON p.id = peopleids.id LEFT JOIN cars on cars.id = peopleids.car;

SELECT
ag.id,
p.first_name,
p.last_name,
p.organisation,
p.event_date,
p.wave
FROM (
SELECT booking.person_1 as id, booking.Car as car FROM booking
union ALL
SELECT booking.person_2 as id, booking.Car as car FROM booking
) as ag
JOIN people p ON people.id = ag.id;
INNER | LEFT JOIN Cars c ON c.ID = ag.car

select people.first_name as firstname,
people.last_name as lastname,
people.organisation,
booking.dated,
booking.car,
booking.slot from booking
left join people on booking.person_1 = people.id
OR
select people.first_name as firstname,
people.last_name as lastname,
people.organisation,
booking.dated,
booking.car,
booking.slot
from booking
left join people on booking.person_1 = people.id or booking.person_2 = people.id
check that...if you still need help will help you

Related

Mysql find the book with the highest rating for each country. If there is a tie "print" the book with the highest number of ratings

I have the following tables:
CREATE TABLE `country` (
`name` VARCHAR(60) NOT NULL,
`code` VARCHAR(3) UNIQUE NOT NULL,
PRIMARY KEY (`code`)
);
CREATE TABLE `user` (
`userId` INT UNIQUE NOT NULL AUTO_INCREMENT,
`country` VARCHAR(3) NOT NULL,
`age` INT NOT NULL,
PRIMARY KEY (`userId`),
CONSTRAINT `fk_user_country` FOREIGN KEY (`country`) REFERENCES `country`(`code`)
);
CREATE TABLE `bookRating` (
`userId` INT NOT NULL,
`isbn` VARCHAR(13) NOT NULL,
`rate` INT NOT NULL,
`date` DATE NOT NULL,
CONSTRAINT `fk_bookRating_user` FOREIGN KEY (`userId`) REFERENCES `user`(`userId`),
CONSTRAINT `fk_bookRating_book` FOREIGN KEY (`isbn`) REFERENCES `book`(`isbn`)
);
CREATE TABLE `book` (
`isbn` varchar(13) UNIQUE NOT NULL,
`bookTitle` VARCHAR(280),
`bookAuthor` VARCHAR(150),
`yearPublication` int(4),
-- `yearPublication` must be an integer because we have value less that 1901 in dataset
`publisher` VARCHAR(135),
PRIMARY KEY (`isbn`),
CONSTRAINT `publication_yea_chk` check ((`yearPublication` > -1) && (`yearPublication` < 2101))
);
As I am saying on the title I want to find the book with the highest average rating, For each country
I have tried this query:
select T1.name, T1.BookTitle, Rate
from
(
select C.Code, AVG(BR.rate) MAXRating
from `bookRating` BR
inner join `book` B on BR.isbn = B.isbn
INNER JOIN `USER` U ON BR.UserID = U.USERId
INNER JOIN `COUNTRY` C ON U.country = C.Code
group by C.Code
) T
inner join
(
select C.Code, C.name, B.BookTitle, BR.ISBN, BR.rate
from `bookRating` BR
inner join `book` B on BR.isbn = B.isbn
INNER JOIN `USER` U ON BR.UserID = U.USERId
INNER JOIN `COUNTRY` C ON U.country = C.Code
) T1 ON T.Code = T1.Code AND T.MAXRATING = T1.RATE;
I am pretty sure this works. But I want to make it like If 2 or more books have the same average rating I want the one with the highest number of ratings.
I figured that I could use an If() statement, but how could I If(... , a condition)
How could I do it?
UPDATE
I have made the database and inserted some info in db fidle:
https://www.db-fiddle.com/f/s6wKhKhxXMX1W2x9VZn9da/1
You can join the tables, aggregate by country and book to get all average ratings and use window functions MAX() and FIRST_VALUE() on the results of the aggregation to get the book with the highest average for each country:
SELECT DISTINCT c.name,
FIRST_VALUE(b.bookTitle) OVER (
PARTITION BY c.Code
ORDER BY AVG(r.rate) DESC, COUNT(*) DESC
) bookTitle,
MAX(AVG(r.rate)) OVER () AverageRating
FROM country c
INNER JOIN users u ON u.country = c.Code
INNER JOIN bookRating r ON r.UserID = u.UserID
INNER JOIN book b ON b.isbn = r.isbn
GROUP BY c.Code, b.isbn;
See the demo.

MySQL: Count in other tables

in my MySQL database I have three tables:
CREATE TABLE favorites (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) NOT NULL,
location_id int(11) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE locations (
id int(20) NOT NULL,
`name` varchar(150) NOT NULL,
pos_lat float NOT NULL,
pos_lon float NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE ratings (
id int(11) NOT NULL AUTO_INCREMENT,
location_id int(11) NOT NULL,
user_id int(11) NOT NULL
stars int(11) NOT NULL,
review text,
PRIMARY KEY (id)
);
Now I want to select some of the locations and calculate the number of ratings, the average number of stars and the number of favorites in an efficient way.
My approach is this one but it gives me totally wrong values for the COUNTs.
SELECT l.id AS location_id,
COUNT(DISTINCT r.id), AVG(r.stars), COUNT(DISTINCT f.id)
FROM locations l, ratings r, favorites f
WHERE (l.id=r.location_id OR l.id=f.location_id)
AND l.id IN (7960,23713,...,18045,24247)
GROUP BY l.id
Can you help me?
The problem has to do with your join condition using OR:
WHERE (l.id=r.location_id OR l.id=f.location_id)
When it finds ONE record where l.id = r.location_id it will be true for ALL rows in f because of the OR. Similarly when it finds 1 record with l.id = f.location_id you will match ALL rows in r.
Instead, use a LEFT JOIN for each of r and f:
SELECT l.id AS location_id,
COUNT(DISTINCT r.id), AVG(r.stars), COUNT(DISTINCT f.id)
FROM locations l
LEFT JOIN ratings r ON (l.id = r.location_id)
LEFT JOIN favorites f ON (l.id = f.location_id)
WHERE l.id IN (7960,23713,...,18045,24247)
GROUP BY l.id

Select 3 tables with count and join

I've 3 tables tb1, users, users_credits.
My gol is to combine two select (sel1, sel2) into a single view and
display 0 in the sel2 where there isn't rows (left join?)
sel1
SELECT
users.userid,
users.datareg,
users_credits.credits,
FROM
users,
users_credits,
WHERE
users.userid = users_credits.userid
Sel2
SELECT COUNT(*) FROM tb1 where tb1.id_user = users.userid
table structure
tb1
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` decimal(11,0) NOT NULL,
`datains` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
users
`userid` int(4) unsigned NOT NULL AUTO_INCREMENT,
`datareg` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`userid`)
users_credits
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) NOT NULL,
`credits` decimal(5,0) NOT NULL,
`data` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
What is the best way to do this?
Thanks.
SELECT users.userid,
users.datareg,
users_credits.credits,
COALESCE(c.totalCount,0) totalCount
FROM users
LEFT JOIN users_credits
ON users.userid = users_credits.userid
LEFT JOIN
(
SELECT id_user, COUNT(*) totalCount
FROM tb1
GROUP BY id_user
) c ON c.id_user = users.userid
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
UPDATE 1
SELECT users.userid,
users.datareg,
users_credits.credits,
COALESCE(c.totalCount,0) totalCount,
c.max_datains
FROM users
LEFT JOIN users_credits
ON users.userid = users_credits.userid
LEFT JOIN
(
SELECT id_user, MAX(datains) max_datains, COUNT(*) totalCount
FROM tb1
GROUP BY id_user
) c ON c.id_user = users.userid
UPDATE 2
you need to create two views for this:
1st View:
CREATE VIEW tbl1View
AS
SELECT id_user, MAX(datains) max_datains, COUNT(*) totalCount
FROM tb1
GROUP BY id_user
2nd View
CREATE VIEW FullView
AS
SELECT users.userid,
users.datareg,
users_credits.credits,
COALESCE(c.totalCount,0) totalCount,
c.max_datains
FROM users
LEFT JOIN users_credits
ON users.userid = users_credits.userid
LEFT JOIN tbl1View c ON c.id_user = users.userid

select the max value and other values from three different tables

I have three tables with the following structure:-
CREATE TABLE `contract` (
`conid` int(11) NOT NULL AUTO_INCREMENT,
`servName` int(11) NOT NULL,
`cid` int(11) NOT NULL,
`term` int(11) DEFAULT NULL,
`monthly_charge` double NOT NULL,
`start_date` date NOT NULL,
`expiry_Date` date NOT NULL,
`next_PayDate` date DEFAULT NULL,
`status` tinyint(4) NOT NULL,
PRIMARY KEY (`conid`),
UNIQUE KEY `servName` (`servName`,`cid`)
)
CREATE TABLE `servicetype` (
`sid` int(11) NOT NULL AUTO_INCREMENT,
`serviceName` varchar(255) NOT NULL,
PRIMARY KEY (`sid`)
)
CREATE TABLE `transactions` (
`tid` int(11) NOT NULL AUTO_INCREMENT,
`conid` int(11) NOT NULL,
`amount` double NOT NULL,
`paidate` date NOT NULL,
`descr` text NOT NULL,
PRIMARY KEY (`tid`)
)
What I want to get is the latest transaction for a particular user i.e:-
conid, serviceName, cid, term, monthly_charge, start_date, expiry_Date, next_PayDate, amount, paidate, descr
And this is the select statement I am using the get to that information:-
SELECT c.conid, serviceName, cid, term, monthly_charge, start_date, expiry_Date, next_PayDate, status, amount, paidate, descr
FROM servicetype s
LEFT JOIN contract c on s.sid = c.servName
LEFT JOIN transactions t ON c.conid=t.conid
WHERE cid = 4 AND status = 1
The statement works but, it is giving me all transactions belonging to cid 4 and all I want to display is only the latest transaction belonging to the said contract it (conid).
Thanking you in advance for your time and effort.
Sounds like you want to use MySQL's GROUP BY to group all of the results by a specific cid, and then use a HAVING condition to get the MAX() transaction:
SELECT
c.conid, serviceName, cid, term, monthly_charge, start_date, expiry_Date, next_PayDate, status, amount, paidate, descr
FROM servicetype s
LEFT JOIN contract c on s.sid = c.servName
LEFT JOIN transactions t ON c.conid=t.conid
WHERE
cid = 4 AND status = 1
GROUP BY cid
HAVING t.paidate = MAX(t.paidate)
You can JOIN twice on the transactions table. The first join gets the max() date for each conid and then the second join will return the details of that max transaction:
select c.conid,
s.serviceName,
c.cid,
c.term,
c.monthly_charge,
c.start_date,
c.expiry_date,
c.next_PayDate,
c.status,
t2.amount,
t1.paidate,
t2.descr
FROM servicetype s
LEFT JOIN contract c
on s.sid = c.servName
LEFT JOIN
(
SELECT max(paidate) paidate, conid
FROM transactions
GROUP BY conid
) t1
ON c.conid=t1.conid
LEFT JOIN transactions t2
ON t1.paidate = t2.paidate
AND t1.conid = t2.conid
WHERE c.cid = 4
AND c.status = 1
Edit, based on your comments the query should be:
select c.conid,
s.serviceName,
c.cid,
c.term,
c.monthly_charge,
c.start_date,
c.expiry_date,
c.next_PayDate,
c.status,
t3.amount,
t3.paidate,
t3.descr
FROM servicetype s
LEFT JOIN contract c
on s.sid = c.servName
LEFT JOIN
(
SELECT max(paidate) paidate, conid, max(tid) tid
FROM transactions t
GROUP BY conid
) t1
on c.conid = t1.conid
LEFT JOIN transactions t3
on t1.conid = t3.conid
and t1.paidate = t3.paidate
and t1.tid = t3.tid
where c.cid = 4
and c.status = 1
GROUP BY c.conid;
See SQL Fiddle With Demo

MySQL joins involving aggregate data

What I require is a SQL query which can report on data from aggregate and singular tables. The current database I have is as follows.
CREATE TABLE IF NOT EXISTS `faults_days` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`employee_id` int(11) NOT NULL,
`day_date` date NOT NULL,
`actioned_calls_out` int(11) NOT NULL,
`actioned_calls_in` int(11) NOT NULL,
`actioned_tickets` int(11) NOT NULL,
)
CREATE TABLE IF NOT EXISTS `faults_departments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
)
CREATE TABLE IF NOT EXISTS `faults_employees` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`team_id` int(11) NOT NULL,
`name` varchar(127) NOT NULL,
)
CREATE TABLE IF NOT EXISTS `faults_qos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`qos_date` datetime NOT NULL,
`employee_id` int(11) NOT NULL,
`score` double NOT NULL,
)
CREATE TABLE IF NOT EXISTS `faults_teams` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`department_id` int(11) NOT NULL,
`name` varchar(40) NOT NULL,
)
A row in Day tracks a single employee's performance for a single day (number of calls taken, number of tickets actioned). A Qos is a measure of an employee's quality on a day (there can be more than one Qos per day - what I need to obtain is the average score). Also, a Qos can be performed on a day where the employee has no performance entry in the database, and this will still need to be shown on the report.
The required end result is 4 reports, which show the employee performance grouped by different columns. A breakdown of a single employee's performance per day, an employee's total performance over a period of time, a team's performance over a period of time, and a whole department's performance over a period of time.
My problem, is that my current queries are a little convoluted, and require two separate queries for the Day data, and the Qos data. My PHP application then combines the data before outputting the report. What I would like, is a single query which returns both total performance, and average quality scores.
The current queries I have to show employee performances are:
SELECT
`Employee`.`name` ,
`Team`.`name` ,
`Department`.`name` ,
SUM( `Day`.`actioned_calls_in` ) + SUM( `Day`.`actioned_calls_out` ) ,
SUM( `Day`.`actioned_tickets` )
FROM
`faults_days` AS `Day`
JOIN
`faults_employees` AS `Employee` ON `Day`.`employee_id` = `Employee`.`id`
JOIN
`faults_teams` AS `Team` ON `Employee`.`team_id` = `Team`.`id`
JOIN
`faults_departments` AS `Department` ON `Team`.`department_id` = `Department`.`id`
WHERE
`Day`.`day_date` >= '2011-06-01'
AND `Day`.`day_date` <= '2011-06-07'
GROUP BY `Employee`.`id`
WITH ROLLUP
and
SELECT
`Employee`.`name` ,
`Team`.`name` ,
`Department`.`name` ,
COUNT( `Qos`.`score` ) ,
AVG( `Qos`.`score` )
FROM
`faults_qos` AS `Qos`
JOIN
`faults_employees` AS `Employee` ON `Qos`.`employee_id` = `Employee`.`id`
JOIN
`faults_teams` AS `Team` ON `Employee`.`team_id` = `Team`.`id`
JOIN
`faults_departments` AS `Department` ON `Team`.`department_id` = `Department`.`id`
WHERE
`Qos`.`qos_date` >= '2011-06-01'
AND `Qos`.`qos_date` <= '2011-06-07'
GROUP BY `Employee`.`id`
WITH ROLLUP
I have also tried simply joining the Qos table, but because it returns multiple rows it messes up the SUM() totals, and also has problems due to the missing FULL OUTER JOIN functionality.
EDIT:
I've made some small progress with this. It looks like using subqueries is the way to go, but everything I'm doing is pure guesswork. Here's what I've got so far, its only showing a row if there's an entry in both the Day and Qos tables, which is not what I want, and I've no idea how to expand it to include the various groupings described above.
SELECT
`Employee`.`name` ,
`Team`.`name` ,
`Department`.`name`,
`Day`.`Calls`,
`Day`.`Tickets`,
`Qos`.`NumQos`,
`Qos`.`Score`
FROM `faults_employees` AS `Employee`
JOIN
`faults_teams` AS `Team` ON `Employee`.`team_id` = `Team`.`id`
JOIN
`faults_departments` AS `Department` ON `Team`.`department_id` = `Department`.`id`
JOIN
(SELECT
`Day`.`employee_id` AS `eid`,
SUM(`Day`.`actioned_calls_in`) + SUM(`Day`.`actioned_calls_out`) AS `Calls`,
SUM(`Day`.`actioned_tickets`) AS `Tickets`
FROM `faults_days` AS `Day`
WHERE
`Day`.`day_date` = '2011-03-02'
GROUP BY `Day`.`employee_id`
) AS `Day`
ON `Day`.`eid` = `Employee`.`id`
JOIN
(SELECT
`Qos`.`employee_id` AS qid,
COUNT(`Qos`.`id`) AS `NumQos`,
AVG(`Qos`.`score`) AS `Score`
FROM `faults_qos` AS `Qos`
WHERE
`Qos`.`qos_date` = '2011-03-02'
GROUP BY `Qos`.`employee_id`
) AS `Qos`
ON `Qos`.`qid` = `Employee`.`id`
GROUP BY `Employee`.`id`
You do want the left joins on the fault_qos and fault_days subqueries. That's what will give you a result even if there isn't a corresponding row in one or both. A left join says that the value is necessary in the table(s) to the left of the join that are involved in the join but not the one on the right. I haven't tested this, and it's late, so I might not be thinking clearly, but if you change your query to this it should work:
SELECT
`Employee`.`name` ,
`Team`.`name` ,
`Department`.`name`,
`Day`.`Calls`,
`Day`.`Tickets`,
`Qos`.`NumQos`,
`Qos`.`Score`
FROM `faults_employees` AS `Employee`
JOIN
`faults_teams` AS `Team` ON `Employee`.`team_id` = `Team`.`id`
JOIN
`faults_departments` AS `Department` ON `Team`.`department_id` = `Department`.`id`
LEFT JOIN
(SELECT
`Day`.`employee_id` AS `eid`,
SUM(`Day`.`actioned_calls_in`) + SUM(`Day`.`actioned_calls_out`) AS `Calls`,
SUM(`Day`.`actioned_tickets`) AS `Tickets`
FROM `faults_days` AS `Day`
WHERE
`Day`.`day_date` = '2011-03-02'
GROUP BY `Day`.`employee_id`
) AS `Day`
ON `Day`.`eid` = `Employee`.`id`
LEFT JOIN
(SELECT
`Qos`.`employee_id` AS qid,
COUNT(`Qos`.`id`) AS `NumQos`,
AVG(`Qos`.`score`) AS `Score`
FROM `faults_qos` AS `Qos`
WHERE
`Qos`.`qos_date` = '2011-03-02'
GROUP BY `Qos`.`employee_id`
) AS `Qos`
ON `Qos`.`qid` = `Employee`.`id`
GROUP BY `Employee`.`id`