Combining 3 querys on SQL - mysql

I have a table with both, Products and Sevices. And I store the products brands, product names and services names on separate tables.
I get the list of Services with this Query:
SELECT maeinvs.idInv, CONCAT(services.Service, " ", maeinvs.Detail) AS Name
FROM maeinvs
INNER JOIN services
ON services.idService = maeinvs.idService
And the list of Products with this one:
SELECT maeinvs.idInv, CONCAT(brands.Brand, " ", products.Product, " ", maeinvs.Detail) AS Name
FROM maeinvs
INNER JOIN products
ON products.idProduct = maeinvs.idProduct
INNER JOIN brands
ON brands.idBrand = maeinvs.idBrand
I need to get a Query like this, but instead of the idInv field I need the actual Name of the Product or Service. Any ideas?
SELECT idInv, Desc, Qnty, Price
FROM invoicedetails
WHERE idInvoice = $id
Thanks.

SELECT maeinvs.idInv, CONCAT(services.Service, " ", maeinvs.Detail) AS Name,
"" AS Desc, 0 AS Qnty, 0 AS Price
FROM maeinvs
INNER JOIN services
ON services.idService = maeinvs.idService
UNION
SELECT maeinvs.idInv, CONCAT(brands.Brand, " ", products.Product, " ", maeinvs.Detail) AS Name,
"" AS Desc, 0 AS Qnty, 0 AS Price
FROM maeinvs
INNER JOIN products
ON products.idProduct = maeinvs.idProduct
INNER JOIN brands
ON brands.idBrand = maeinvs.idBrand
UNION
SELECT idInv,
"" AS Name,
Desc, Qnty, Price
FROM invoicedetails
WHERE idInvoice = $id
I've written what I've changed on next line
As the columns match each other, UNION will work.

I still don't know how to do it on a single query (I just know the basics; an Alias?) but solved it doing a VIEW and then a JOIN with my invoicedetails table.
VIEW:
SELECT maeinvs.idInv, CONCAT(services.Service, " ", maeinvs.Detail) AS Name
FROM maeinvs
INNER JOIN services
ON services.idService = maeinvs.idService
UNION
SELECT maeinvs.idInv, CONCAT(brands.Brand, " ", products.Product, " ", maeinvs.Detail) AS Name
FROM maeinvs
INNER JOIN products
ON products.idProduct = maeinvs.idProduct
INNER JOIN brands
ON brands.idBrand = maeinvs.idBrand
QUERY:
SELECT viewnames.Name, invoicedetails.Desc, invoicedetails.Qnty, invoicedetails.Price
FROM invoicedetails
INNER JOIN viewnames ON viewnames.idInv = invoicedetails.idInv
WHERE invoicedetails = $id

Related

How do I display two columns with multiple values and separate the occurances with a WHERE clause

This is my SQL query I am trying to select the names of employees from the employee table 'T' as trainer and 'S' as student. Where each student is linked to a trainer.
SQL query:
SELECT
cc.CourseName,
FORMAT(cs.StartDate, 'dd/MM/yyyy') AS 'Start Date',
FORMAT(cs.EndDate, 'dd/MM/yyyy') AS 'End Date',
a.AcademyName,
r.RoomName,
(SELECT e.FirstName + ' ' + e.LastName WHERE e.EmployeeType = 'T') AS 'Trainer',
(SELECT e.FirstName + ' ' + e.LastName WHERE e.EmployeeType = 'S') AS 'Student'
FROM
Employees e
INNER JOIN
CourseScheduleTrainers cst ON e.EmployeeID = cst.EmployeeID
INNER JOIN
CourseScheduleAttendees csa ON cst.TrainerID = csa.TrainerID
INNER JOIN
CourseCatalog cc ON csa.CourseCatalogID = cc.CourseCatalogID
INNER JOIN
CourseSchedule cs ON cc.CourseScheduleID = cs.CourseScheduleID
INNER JOIN
Rooms r ON cs.RoomsID = r.RoomsID
INNER JOIN
Academies a ON r.AcademyID = a.AcademyID;
This is what it is returning:
And this is an ERD of the database I am am trying to create. Essentially Course Attendees can also be classed as employees and they are labelled using the Employee Type
Entity Relationship Diagram:
I thought it was a simple case of sub querying but that doesn't seem to work.
Consider joining Employees twice and re-order the FROM and JOIN clauses to start with the main granular table, CourseScheduleAttendees, where other tables serve as lookups in a hub-spoke fashion:
SELECT cc.CourseName
,FORMAT(cs.StartDate, 'dd/MM/yyyy') AS 'Start Date'
,FORMAT(cs.EndDate, 'dd/MM/yyyy') AS 'End Date'
,a.AcademyName
,r.RoomName
,t.FirstName + ' ' + t.LastName AS 'Trainer'
,s.FirstName + ' ' + s.LastName AS 'Student'
FROM CourseScheduleAttendees csa
INNER JOIN CourseScheduleTrainers cst
ON csa.TrainerID = cst.TrainerID
INNER JOIN Employees t
ON cst.EmployeeID = t.EmployeeID
AND t.EmployeeType = 'T'
INNER JOIN Employees s
ON csa.AttendeeID = s.EmployeeID
AND s.EmployeeType = 'S'
INNER JOIN CourseCatalog cc
ON csa.CourseCatalogID = cc.CourseCatalogID
INNER JOIN CourseSchedule cs
ON cc.CourseScheduleID = cs.CourseScheduleID
INNER JOIN Rooms r
ON cs.RoomsID = r.RoomsID
INNER JOIN Academies a
ON r.AcademyID = a.AcademyID;

Join 2 query in different as different column

I need to join 2 queries within a database but place it in 2 different column
i tried union but the result are in the same column "total fulltime"
(SELECT (SUM(servicehours) + SUM(`teachinghours`) + SUM(`researchhours`)) as 'Total fulltime'
FROM staff_hour sh,staff s,role r
WHERE r.roleid =s.roleid
AND s.staffid = sh.staffid
AND r.roleid='2'
AND sh.staffperiodyear = 'FY2018')
union
(SELECT (SUM(servicehours) + SUM(`teachinghours`) + SUM(`researchhours`)) as 'Total parttime'
FROM staff_hour sh,staff s,role r
WHERE r.roleid =s.roleid
AND s.staffid = sh.staffid
AND r.roleid='3'
AND sh.staffperiodyear = 'FY2018')
How do i join it so that there are 2 different column('total fulltime' & 'total parttime') with the total sum?
You could use your queries with cross join
select t1.Total_fulltime
, t2.Total_parttime
, t1.Total_fulltime + t2.Total_parttime total_sum
from (SELECT (SUM(servicehours) + SUM(`teachinghours`) + SUM(`researchhours`)) as Total_fulltime
FROM staff_hour sh,staff s,role r
WHERE r.roleid =s.roleid
AND s.staffid = sh.staffid
AND r.roleid='2'
AND sh.staffperiodyear = 'FY2018') t1
CROSS JOIN
(SELECT (SUM(servicehours) + SUM(`teachinghours`) + SUM(`researchhours`)) as Total_parttime
FROM staff_hour sh,staff s,role r
WHERE r.roleid =s.roleid
AND s.staffid = sh.staffid
AND r.roleid='3'
AND sh.staffperiodyear = 'FY2018') t2

mysql joining two table without in common

i have this script.. first i run query 1 and store into array then query 2,
using a foreach, i combine them and create a list of urls..but this takes time.. is there a way i can do this just in mysql by combining the table even do they have no common column?
query 1
SELECT
c.id,
c.city_name,
r.region_name,
cr.country_name
FROM city AS c, region AS r, country AS cr
WHERE r.id = c.id_region
AND cr.id = c.id_country
AND cr.id IN
(SELECT id FROM country WHERE used = 1)
query 2
SELECT id, title FROM param WHERE active = 1
loop
foreach ($arrayCity as $city) {
foreach ($arrayParam as $param ) {
$paramTitle = str_replace(' ', '+', $param['title']);
$url = 'http://url/city/'. $city['id'] .'/paramId/'. $param['id'] .'/'.
$paramTitle .'/'. $city['region_name'] .'/'. $city['city_name'];
}
}
You don't have to join on a condition. Not doing so is called a CROSS JOIN. The CROSS keyword is optional. In fact, you are already doing this because , is a synonym.
FROM city AS c, region AS r, country AS cr, param
How about
Select 'http://url/city/' + c.id + '/paramId/' + p.id + '/' +
Replace(title, ' ', '+') + '/' + r.region_Name + '/' + c.city_Name
From city c
Join region r On r.id = c.id_region
Join country n On n.id = c.id_country
cross join param p
Where n.Uused = 1
And p.active = 1
Something like this. You can select a concatenated string with results from your base table.
SELECT
c.id,
c.city_name,
r.region_name,
cr.country_name,
('http://url/city/' + c.city_name + '/' + p.param + '/' + c.id) AS URL
FROM city AS c, region AS r, country AS cr
JOIN param p ON c.id = p.id
WHERE r.id = c.id_region AND cr.id = c.id_country AND cr.id IN (SELECT id FROM country WHERE used = 1)
My experience is in TSQL, but it'll be close in my SQL
Edit: Sorry, forgot the join

SUM() on all rows of a LEFT JOIN?

I've been playing with LEFT JOINs and I'm wondering if it's possible to get the SUM of all the ratings so far from all users in the below query. The below get's me the information on if the logged in user has rated or not, but i want to show total ratings from other users also.
$query = mysql_query("
SELECT com.comment, com.comment_id, r.rate_up, r.rate_down
FROM comments com
LEFT JOIN ratings r
ON com.comment_id = r.comment_id
AND r.user_id = '" . $user_id_var . "'
WHERE page_id = '" . $category_id_var. "'");
I've tried the following but i only get one comment/row returned for some reason.
$query = mysql_query("
SELECT com.comment, com.comment_id,
r.rate_up, r.rate_down
SUM(r.rate_up) AS total_up_ratings,
SUM(r.rate_down) AS total_down_ratings,
FROM comments com
LEFT JOIN ratings r
ON com.comment_id = r.comment_id
AND r.user_id = '" . $user_id_var . "'
WHERE page_id = '" . $category_id_var. "'");
Any help appreciated. Do i need a different kind of JOIN?
Have you tried using GROUP BY page_id on the end of your SQL?
You could do it something like this:
SELECT
com.comment,
com.comment_id,
Total.total_down_ratings,
Total.total_up_ratings
FROM comments com
LEFT JOIN
(
SELECT
SUM(r.rate_up) AS total_up_ratings,
SUM(r.rate_down) AS total_down_ratings,
r.comment_id
FROM
ratings r
GROUP BY
r.comment_id
) AS Total
ON com.comment_id = Total.comment_id
AND r.user_id = '" . $user_id_var . "'
WHERE page_id = '" . $category_id_var. "'"
If you use an aggregation function in SQL (like SUM()) you will need a corresponding GROUP BY clause.
In your case the most likely one would be com.comment_id; this will give you the sum of all ratings per comment_id:
I don't know if you are duplicating comment rows for purpose but if not you can try write subselect for ratings like this:
select comment_id, user_id, sum(rate_up) as sum_rate_up,
sum(rate_down) as sum_rate_down from ratings
group_by comment_id, user_id;
and then include it in your join query:
select com.comment, com.comment_id, r.user_id, r.sum_rate_up,
r.sum_rate_down from comments com
left join (select comment_id, user_id, sum(rate_up) as sum_rate_up,
sum(rate_down) as sum_rate_down from ratings
group_by comment_id, user_id) as r
on com.comment_id = r.comment_id where page_id = '".$category_id_var."'

Duplicate column name 'user_id' problem

I'm having a problem trying to count the number of user records according to the user's id, however I'm using a subquery to join 2 tables that one has a count parameter but I get an error saying duplicate column name 'user_id.
The query:
$sql = "SELECT loc.location_id,
COUNT(loc.location_id) AS total_records
FROM locations loc
LEFT JOIN
(
SELECT usr.*,
loc.*
FROM
(
members usr
INNER JOIN locations loc
)
WHERE usr.user_id = " . $user_id . "
AND usr.account_disabled = 0
ORDER BY loc.submit_date DESC
) usr ON (loc.user_id = usr.user_id)";
All I need it is to return the user's info and the total_records count done by the COUNT function.
Cheers.
EDIT:
This is what I get returned for this SQL:
SELECT loc.location_id,
loc.street_name,
loc.city,
loc.state,
loc.county,
loc.country,
usr.user_id,
usr.username,
COUNT(loc.location_id) AS total_records
FROM locations loc
INNER JOIN members usr ON (loc.user_id = usr.user_id)
WHERE loc.user_id = $user_id
AND usr.account_disabled = 0
GROUP BY loc.location_id
It's not exactly clear why you've got the derived resultset or the LEFT JOIN. Try this:
SELECT loc.location_id,
COUNT(loc.location_id) AS total_records
FROM LOCATIONS_TABLE loc
INNER JOIN MEMBERS_TABLE usr
ON (loc.user_id = usr.user_id)
WHERE loc.user_id = $user_id
AND usr.account_disabled = 0
GROUP BY loc.location_id
I think the problem is this part:
SELECT usr.*,
loc.*
Both tables have a user_id