How to user Left join with three tables ?mysql - mysql

I have this query :
SELECT bussiness.bussId , count(favourites.userID) as fav
from `bussiness`
LEFT JOIN `favourites` on (`bussiness`.`bussId` = `favourites`.`bussId`)
where bussiness.bussId= 12310
when I run this query I get fav = 2.
but when I Left join another table ,
SELECT bussiness.bussId , count(favourites.userID) as fav from `bussiness`
LEFT JOIN `favourites` on (`bussiness`.`bussId` = `favourites`.`bussId`)
LEFT JOIN `invoices` on (`bussiness`.`bussId` = `invoices`.`bussId`)
where bussiness.bussId= 12310
I get fav = 88 instead of 2
why this happened ?

It appears as if there are multiple occurrences of bussId in the hello table causing the number of rows returned to multiply. Since you were not doing a distinct count of userID, the query was simply counting the number of rows that contain a userID. If you want to count the number of unique users, you need to use COUNT DISTINCT. Like this:
SELECT bussiness.bussId , count(distinct favourites.userID) as fav from `bussiness`
LEFT JOIN `favourites` on (`bussiness`.`bussId` = `favourites`.`bussId`)
LEFT JOIN `hello` on (`bussiness`.`bussId` = `hello`.`bussId`)
where bussiness.bussId= 12310

Related

How to handle SQL joins if missing rows on particular table exist

SELECT
fromData.name as fromname, toData.name as toName, prodData.prodname,
t1.`from_id`, t1.`to_id` , t1.`product_id` , t1.`title`, t1.`message`, t1.`senttime` , t1.`readstatus`, t1.`responded`, t1.`merchanthidden`
FROM `inquiries` as t1
INNER JOIN users as fromData on t1.from_id = fromData.id
INNER JOIN users as toData on t1.to_id = toData.id
INNER JOIN products as prodData on t1.product_id = prodData.id
WHERE t1.id=13
Above query joins 3 tables (inquiries, users, products) together and gets data from each table.
Sometimes it is possible that items in the 'products' table get deleted. Trying to join products table by a deleted product id will fail the query.
Is there a way that I can assign 'prodData.prodname' a default value and execute query without failing in case of a missing item in products table ?
Why don't use left join insted of inner join ,
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match.
SELECT
fromData.name as fromname, toData.name as toName, prodData.prodname,
t1.`from_id`, t1.`to_id` , t1.`product_id` , t1.`title`, t1.`message`, t1.`senttime` , t1.`readstatus`, t1.`responded`, t1.`merchanthidden`
FROM `inquiries` as t1
INNER JOIN users as fromData on t1.from_id = fromData.id
INNER JOIN users as toData on t1.to_id = toData.id
LEFT JOIN products as prodData on t1.product_id = prodData.id
WHERE t1.id=13

Combining two SQL queries with multiple tables and left joins

Is there a way that I can combine these two queries:
FIRST QUERY
select top 100
WORK.pzInsKey,
WORK.pyID,
PARTY.MacID,
PARTY.OtherPartyID,
PARTY.CustomerEmail,
ACCOUNT.AccountNumber,
ACCOUNT.AccountName,
ACCOUNT.AdviserCode,
ACCOUNT.AdviserName,
ACCOUNT.DealerCode,
ACCOUNT.DealerName,
ACCOUNT.PrimaryAccount,
ACCOUNT.ProductCategory,
ACCOUNT.ProductCode,
ACCOUNT.ProductDescription,
ACCOUNT.RegisteredState,
DOCUMENT.UDOCID
from
workTable WORK,
partyTable PARTY,
accountTable ACCOUNT,
documentTable DOCUMENT,
notesTable NOTES
where WORK.pzInsKey = PARTY.pxInsIndexedKey
and WORK.pzInsKey = ACCOUNT.pxInsIndexedKey
and WORK.pyID = DOCUMENT.CaseID
and SECOND QUERY
SELECT top 100
BusinessAreaTbl.businessarea,
ProcessTbl.process,
SubProcessTbl.subprocess
FROM workTable WORK
LEFT OUTER JOIN (SELECT DISTINCT Product_ID businessarea_id, Product businessarea from CaseTypesTable) BusinessAreaTbl
ON WORK.RequestBusinessArea#1 = BusinessAreaTbl.businessarea_id
LEFT OUTER JOIN (SELECT DISTINCT Process_ID, Process, Product_ID businessarea_id from CaseTypesTable) ProcessTbl
ON WORK.RequestProcess#1 = ProcessTbl.process_id
AND ProcessTbl.businessarea_id = WORK.RequestBusinessArea#1
LEFT OUTER JOIN (SELECT DISTINCT SubProcess_ID, SubProcess, Product_ID businessarea_id, Process_ID from CaseTypesTable) SubProcessTbl
ON WORK.RequestSubProcess#1 = SubProcessTbl.subprocess_id
AND SubProcessTbl.businessarea_id = WORK.RequestBusinessArea#1
AND SubProcessTbl.process_id = WORK.RequestProcess#1
It's basically two queries which produce separate results, but each query includes data from the workTable. In the 2nd query, the workTable data is derived from the CaseTypesTable.
I essentially just want the businessarea, process, and subprocess fields to be included with the results of the first query.
Thanks in advance for any help.
This should work:
(SELECT top 100
w.pzInsKey,
w.pyID,
p.MacID,
p.OtherPartyID,
p.CustomerEmail,
a.AccountNumber,
a.AccountName,
a.AdviserCode,
a.AdviserName,
a.DealerCode,
a.DealerName,
a.PrimaryAccount,
a.ProductCategory,
a.ProductCode,
a.ProductDescription,
a.RegisteredState,
d.UDOCID
FROM workTable w
LEFT JOIN partyTable p
ON w.pzInsKey = p.pxInsIndexedKey
LEFT JOIN accountTable a
ON w.pzInsKey = a.pxInsIndexedKey
LEFT JOIN documentTable d
ON w.pyID = d.CaseID)
UNION
(SELECT top 100
ba.businessarea,
pr.process,
spr.subprocess
FROM workTable w
LEFT OUTER JOIN (SELECT DISTINCT Product_ID businessarea_id, Product businessarea from CaseTypesTable) BusinessAreaTbl ba
ON w.RequestBusinessArea#1 = ba.businessarea_id
LEFT OUTER JOIN (SELECT DISTINCT Process_ID, Process, Product_ID businessarea_id from CaseTypesTable) ProcessTbl pr
ON w.RequestProcess#1 = pr.process_id
AND pr.businessarea_id = w.RequestBusinessArea#1
LEFT OUTER JOIN (SELECT DISTINCT SubProcess_ID, SubProcess, Product_ID businessarea_id, Process_ID from CaseTypesTable) SubProcessTbl spr
ON w.RequestSubProcess#1 = spr.subprocess_id
AND spr.businessarea_id = w.RequestBusinessArea#1
AND spr.process_id = w.RequestProcess#1))
Use the keyword UNION to combine two or more seperate SELECT statements.

MySQL get rest of values

Using this query
SELECT DISTINCT(job_primary.id) AS id
FROM `job_primary`
LEFT JOIN `job_skill` ON `job_skill`.`job_id` = `job_primary`.`id`
LEFT JOIN `job_facts` ON `job_facts`.`job_id` = `job_primary`.`id`
LEFT JOIN `job_location` ON `job_location`.`job_id` = `job_primary`.`id`
LEFT JOIN `job_people` ON `job_people`.`job_id` = `job_primary`.`id`
LEFT JOIN `job_sec` ON `job_sec`.`job_id` = `job_primary`.`id`
AND job_sec.exp_start_date > UNIX_TIMESTAMP()
INNER JOIN `user_skills` ON `user_skills`.`skill_id` = `job_skill`.`skill_id`
AND user_skills.user_id = 1
WHERE job_primary.posted_by != 1
I am getting only the id value. But I want to get the rest of the values with distinct id. Don't think about rest of the codes. The problem is here, if I use:
select *, job_primary.id as id
to select code then I get all data. But it is not distinct. So if I used
SELECT *, distinct(job_primary.id) as id
or
SELECT distinct(job_primary.id), * as id
but it is showing errors.
I think your confussion is what to query itself, nixon1333. What do you want to ask to the database? If you want just one row per id, group'em by with SELECT * FROM ... GROUP BY job_primary.id

mysql several count and join returns strange value

I'm trying to make a count within several table with JOIN, but when I made several JOINs the COUNTs got wrongly counted.
Basically I've got 4 tables, named:
predective_search
predective_to_product
predective_to_category
predective_to_manufacturer
I want to count the total number of products, categories and manufacturer which has same id in table predective_search.
Here's my code:
SELECT * ,
COUNT(pp.predictive_id) AS total_products,
COUNT(pc.predictive_id) AS total_categories,
COUNT(pm.predictive_id) AS total_manufacturers
FROM predictive_search ps
LEFT JOIN predictive_to_product pp ON (ps.predictive_id = pp.predictive_id)
LEFT JOIN predictive_to_category pu ON (ps.predictive_id = pc.predictive_id)
LEFT JOIN oc_predictive_to_manufacturer pm ON (ps.predictive_id = pm.predictive_id)
GROUP BY ps.predictive_id
Also the GROUP BY is needed I think. I'm stuck at this as I'm not getting any way to do this
SELECT
ps.*,
agg_pp.total_products,
agg_pc.total_categories,
agg_pm.total_manufacturers
FROM predictive_search ps
LEFT JOIN (
SELECT pp.predictive_id, COUNT(*) AS total_products
FROM predictive_to_product pp
GROUP BY pp.predictive_id
) agg_pp ON ps.predictive_id = agg_pp.predictive_id
LEFT JOIN (
SELECT pc.predictive_id, COUNT(*) AS total_categories
FROM predictive_to_category pc
GROUP BY pc.predictive_id
) agg_pc ON ps.predictive_id = agg_pc.predictive_id
LEFT JOIN (
SELECT pm.predictive_id, COUNT(*) AS total_manufacturers
FROM predictive_to_category pm
GROUP BY pm.predictive_id
) agg_pm ON ps.predictive_id = agg_pm.predictive_id

MySQL SELECT DISTINCT ORDER BY problem

To begin with I have 4 tables I am dealing with.
I have a classes table that is a 1->N relationship with a sections table which also has a 1->N relationship with a lessons table.
So to put it in perpective:
Classes
Sections
Lessons
The last table is an activityLog, when the student accesses a lesson this is recorded using the following:
ActivityLog Row -> actorID (user ID), classID, sectionID, lessonID
I want to pull out the last 5 unique lessons the student has visited. I tried using both DISTINCT and GROUP BY without success.
The same records are being returned each time, not the latest classes that they have visited.
Using GROUP BY
SELECT activityLog.actorID, activityLog.activityDate,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
GROUP BY activityLog.lessonID
ORDER BY activityLog.activityDate DESC
LIMIT 5
Using DISTINCT
SELECT DISTINCT activityLog.actorID,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
ORDER BY activityLog.activityDate DESC
LIMIT 5
I cannot figure out why the latest records are not being displayed.
Based on your change, how does this suit you?
SELECT activityLog.actorID, activityLog.activityDate,
strClasses.classID, strClasses.className,
strSections.sectionID, strSections.sectionName,
strLessons.lessonID, strLessons.lessonName
FROM activityLog
LEFT JOIN strClasses ON strClasses.classID = activityLog.classID
LEFT JOIN strSections ON strSections.sectionID = activityLog.sectionID
LEFT JOIN strLessons ON strLessons.lessonID = activityLog.lessonID
WHERE activityLog.activityTypeID = 6 AND activityLog.actorID = 3
AND activityLog.activityDate = (SELECT MAX(activityDate) FROM activityLog AS lookup WHERE lessonID = activityLog.lessonID)
ORDER BY activityLog.activityDate DESC
LIMIT 5
Based on your description, I'm not sure why you're using LEFT JOIN, but I've left it in just in case.
Try group by like below
GROUP BY activityLog.classID,activityLog.sectionID,activityLog.lessonID
I think it will work, or just sent me create scripts for these I will create that query
Well, there's got to be a datetime in the ActivityLog I hope... so Try this:
Select s.Name, c.ClassName
From Students s
left Join On Classes c
On c.ClassId In
(Select Distinct ClassId From Classes
Where (Select Count(Distinct ClassId) From Classes ic
Join ActivityLog l On l.UserId = s.UserId
And l.ClassId = c.ClassId
Where classId = c.ClassId
And activityDateTime > l.activityDateTime)
< 5)