Joining mutiple select statements in one SQL statement - mysql

I am trying to join two sql statements into one but have had no success.
I would ideally like the Average query to be added to the end of the columns from the first sql statement.
First statement:
SELECT Modules.UserID, Module_Info.ModuleTitle, Modules.ModuleMarks, Modules.ExamMark, Modules.AssignmentMark, MarkClassification.MarkDescription
FROM Module_Info
INNER JOIN Modules ON Module_Info.ModuleID = Modules.ModuleID
INNER JOIN MarkClassification ON Modules.MarkCodeDescription = MarkClassification.MarkId
WHERE(Modules.UserID = '8')
Second statement:
SELECT AVG(Modules.ExamMark) AS Average
FROM Module_Info
INNER JOIN Modules ON Module_Info.ModuleID = Modules.ModuleID
WHERE (Modules.ModuleID = '2')

You can use a sub query in the select for that, like this:
SELECT Modules.UserID, Module_Info.ModuleTitle, Modules.ModuleMarks,
Modules.ExamMark, Modules.AssignmentMark, MarkClassification.MarkDescription,
(SELECT AVG(Modules.ExamMark)
FROM Module_Info
INNER JOIN Modules ON Module_Info.ModuleID = Modules.ModuleID
WHERE (Modules.ModuleID = '2')) as Average
FROM Module_Info
INNER JOIN Modules
ON Module_Info.ModuleID = Modules.ModuleID
INNER JOIN MarkClassification
ON Modules.MarkCodeDescription = MarkClassification.MarkId
WHERE(Modules.UserID = '8')

you can try
SELECT * FROM
(SELECT Modules.UserID, Module_Info.ModuleTitle, Modules.ModuleMarks, Modules.ExamMark, Modules.AssignmentMark, MarkClassification.MarkDescription
FROM Module_Info
INNER JOIN Modules ON Module_Info.ModuleID = Modules.ModuleID
INNER JOIN MarkClassification ON Modules.MarkCodeDescription = MarkClassification.MarkId
WHERE(Modules.UserID = '8')) t1
JOIN
(SELECT AVG(Modules.ExamMark) AS Average
FROM Module_Info
INNER JOIN Modules ON Module_Info.ModuleID = Modules.ModuleID
WHERE (Modules.ModuleID = '2')) t2
Since you do not have a join condition, it will create a cartesian product of the two queries (i.e. each row of the first subselect, with each row of the second subselect). Since the 2nd subselect only has one row, it will give you your expected result.

Related

Do I need a MySQL sub query? How can I get these results?

First, the table names and layouts:
Here are my desired results:
Here is the 'got ya' (trick) I guess..
I will only be passing a (dynamic) imis_id/user_id (col names currently not matching on one table)...
So a lookup (select) will need to be done on the relations table for that passed in (dynamic) id.. and where current_org = 1.
This will get/give me the target org_id in which I need to grab all user info (that are associated with the org_id).. and all org details.
Here is one weak/failed attempt: (it uses a hardcoded org_id) which is not valid.. I need to ONLY pass in the user_id/imis_id.. and where current_org = 1 to get the target org_id.
SELECT genealogy_orgs.org_id, genealogy_orgs.org_name,
genealogy_relations.user_id, genealogy_relations.relation_type, genealogy_relations.start_year, genealogy_relations.end_year,
genealogy_users.imis_id, genealogy_users.full_name
FROM genealogy_orgs
INNER JOIN genealogy_relations ON genealogy_orgs.org_id = genealogy_relations.org_id
INNER JOIN genealogy_users ON genealogy_relations.user_id = genealogy_users.imis_id
WHERE genealogy_orgs.org_id = '84864';
Here is another failed attempt (which only returns 1 row).. but uses the correct criteria:
SELECT
genealogy_relations.org_id,
genealogy_relations.user_id, genealogy_relations.relation_type, genealogy_relations.start_year, genealogy_relations.end_year,
genealogy_users.imis_id, genealogy_users.full_name,
genealogy_orgs.org_name
FROM genealogy_relations
INNER JOIN genealogy_orgs ON genealogy_relations.org_id = genealogy_orgs.org_id
INNER JOIN genealogy_users ON genealogy_relations.user_id = genealogy_users.imis_id
WHERE genealogy_relations.user_id = '00003' AND genealogy_relations.current_org = '1';
At this point, I'm not even sure what I need to search for? Is this where a 'sub-query/sub-select' comes into play?
My MySQL-fu is limited to very direct/plain-jane query types. This is getting to be more advanced than I am used to.
You need to join the genealogy_relations table with itself on org_id:
SELECT o.*, u.*
FROM genealogy_relations r1
JOIN genealogy_relations r2 ON r2.org_id = r1.org_id
JOIN genealogy_orgs o ON o.org_id = r2.org_id
JOIN genealogy_users u ON u.imis_id = r2.user_id
WHERE r1.user_id = '00003'
AND r1.current_org = '1'
Remove the genealogy_relations.user_id = '00003' from the query and it should work
SELECT
genealogy_relations.org_id,
genealogy_relations.user_id, genealogy_relations.relation_type, genealogy_relations.start_year, genealogy_relations.end_year,
genealogy_users.imis_id, genealogy_users.full_name,
genealogy_orgs.org_name
FROM genealogy_relations
INNER JOIN genealogy_orgs ON genealogy_relations.org_id = genealogy_orgs.org_id
INNER JOIN genealogy_users ON genealogy_relations.user_id = genealogy_users.imis_id
WHERE genealogy_relations.current_org = '1';

Issue understanding the Inner Join Or Left join

I am having an issue understanding the inner and left join
I am having the below query in the outsystems
SELECT {CLD}.[Id], {CLD}.[Name], {CLD}.[Comments]
, {CLD}.[LastUpdateOn],min({Project}.[Number])
,count({Project}.[Number])
FROM {CLD}
INNER JOIN {Project} ON {Project}.[Id] = {CLDProjects}.[ProjectId]
INNER JOIN {CLDProjects} ON {CLD}.[Id] = {CLDProjects}.[CLDId]
WHERE
(
#IsJAXPM =1
or EXISTS (SELECT 1
FROM {CLDParticipant}
WHERE {CLDParticipant}.[CLDId] = {CLD}.[Id]
AND {CLDParticipant}.[UserId] = #UserId)
or EXISTS (SELECT 1
FROM {ProjectParticipantWidget}
INNER JOIN {ProjectParticipant} ON {ProjectParticipantWidget}.[ProjectParticipantId] = {ProjectParticipant}.[Id]
WHERE {ProjectParticipant}.[ProjectId] = {Project}.[Id]
AND {ProjectParticipant}.[UserId] = #UserId)
)
GROUP BY {CLD}.[Id], {CLD}.[Name], {CLD}.[Comments], {CLD}.[LastUpdateOn]
The issue is the Select is pulling all the CLD elements without respect to the Project, I am trying to select CLD's whose Project id = Project.Id. I tried both the joins but it keep pulling all the values
Below how the structure looks like
Please try the following: First get the CLDProjects matching with Project then get the CLD from matched records.
FROM {CLD} INNER JOIN (
{CLDProjects} INNER JOIN {Project} ON {Project}.[Id] = {CLDProjects}.[ProjectId]
) ON {CLD}.[Id] = {CLDProjects}.[CLDId]
You're probably missing the inner join to CLDProjects on the ProjectParticipant subquery. Add
INNER JOIN {CLDProjects} ON {ProjectParticipant}.[ProjectId] = {CLDProjects}.[ProjectId])
on the second EXISTS join conditions, otherwise it will the second results will match the exists for every project the user is in, ignoring the other conditions over CLDProjects. Try the following:
SELECT {CLD}.[Id], {CLD}.[Name], {CLD}.[Comments]
, {CLD}.[LastUpdateOn],min({Project}.[Number])
,count({Project}.[Number])
FROM {CLD}
INNER JOIN {Project} ON {Project}.[Id] = {CLDProjects}.[ProjectId]
INNER JOIN {CLDProjects} ON {CLD}.[Id] = {CLDProjects}.[CLDId]
WHERE
(
#IsJAXPM =1
or EXISTS (SELECT 1
FROM {CLDParticipant}
WHERE {CLDParticipant}.[CLDId] = {CLD}.[Id]
AND {CLDParticipant}.[UserId] = #UserId)
or EXISTS (SELECT 1
FROM {ProjectParticipantWidget}
INNER JOIN {ProjectParticipant} ON {ProjectParticipantWidget}.[ProjectParticipantId] = {ProjectParticipant}.[Id]
INNER JOIN {CLDProjects} ON {ProjectParticipant}.[ProjectId] = {CLDProjects}.[ProjectId]
WHERE {ProjectParticipant}.[ProjectId] = {Project}.[Id]
AND {ProjectParticipant}.[UserId] = #UserId)
)
GROUP BY {CLD}.[Id], {CLD}.[Name], {CLD}.[Comments], {CLD}.[LastUpdateOn]
Also.. make sure you're not passing #IsJAXPM as 1... otherwise it will definitely return all records.
Let us know if that works. Otherwise, please extend the diagram to show the ProjectParticipant and ProjectParticipantWidget tables as well.
I think you just need to reorder your joins, I tried to reproduce your case (with incorrect joins order), but it gives me error when test the query,
but if you reorder the the joins, it works. note that I am using OutSystems 10

Sort data in inner join query

select Distinct
_Ad.ad_id, _Ad.Ad_Name,
ID.Image_Path, VM.year,
VD.Vehicle_Transformation, VD.Vehicle_Fuel_Type, VD.Vehicle_Mileage
from
_Ad
order by
Ad_Date_Created
inner join
_Image_Details ID on ID.ad_id = _Ad.ad_id
inner join
_Vehicle_Model VM on VM.vehicle_model_id = _AD.vehicle_model_id
inner join
_Vehicle_Details VD on _ad.ad_id = VD.ad_id;
I keep getting an error that multi part data can not be bound. Please help to correct query
Try this:
select Distinct
_Ad.ad_id, _Ad.Ad_Name,
ID.Image_Path, VM.year,
VD.Vehicle_Transformation, VD.Vehicle_Fuel_Type, VD.Vehicle_Mileage
from
_Ad
inner join
_Image_Details ID on ID.ad_id = _Ad.ad_id
inner join
_Vehicle_Model VM on VM.vehicle_model_id = _AD.vehicle_model_id
inner join
_Vehicle_Details VD on _ad.ad_id = VD.ad_id;
order by
Ad_Date_Created
The syntax of your SQL statement is wrong. An ORDER BY clause should come after the JOIN's

Hanging mysql query

I'm having an issue with the following query
select
ord.order_id,
ordProduct.product_id,
coupProd.product_id,
coup.date_end as DateEnd, coup.coupon_id
from `order` ord
inner join order_product ordProduct on ord.order_id = ordProduct.order_id
inner join coupon_product coupProd on ordProduct.product_id = coupProd.product_id
inner join coupon coup on coupProd.coupon_id = coup.coupon_id
where (coup.date_end > curdate());
If I remvove the where clause, the query executes fine, otherwise it just hangs. Any ideas?
It's not a solution per se, but as a workaround, you could maybe get it done as a nested query. i.e. ,
SELECT * FROM (
SELECT
ord.order_id,
ordProduct.product_id,
coupProd.product_id,
coup.date_end AS DateEnd, coup.coupon_id
FROM `order` ord
INNER JOIN order_product ordProduct ON ord.order_id = ordProduct.order_id
INNER JOIN coupon_product coupProd ON ordProduct.product_id = coupProd.product_id
INNER JOIN coupon coup ON coupProd.coupon_id = coup.coupon_id)
WHERE (DateEnd > CURDATE());

SQL - Multiple many-to-many relations filtering SELECT

These are my tables:
Cadastros (id, nome)
Convenios (id, nome)
Especialidades (id, nome)
Facilidades (id, nome)
And the join tables:
cadastros_convenios
cadastros_especialidades
cadastros_facilidades
The table I'm querying for: Cadastros
I'm using MySQL.
The system will allow the user to select multiple "Convenios", "Especialidades" and "Facilidades". Think of each of these tables as a different type of "tag". The user will be able to select multiple "tags" of each type.
What I want is to select only the results in Cadastros table that are related with ALL the "tags" from the 3 different tables provided. Please note it's not an "OR" relation. It should only return the row from Cadastros if it has a matching link table row for EVERY "tag" provided.
Here is what I have so far:
SELECT Cadastro.*, Convenio.* FROM Cadastros AS Cadastro
INNER JOIN cadastros_convenios AS CadastrosConvenio ON(Cadastro.id = CadastrosConvenio.cadastro_id)
INNER JOIN Convenios AS Convenio ON (CadastrosConvenio.convenio_id = Convenio.id AND Convenio.id IN(2,3))
INNER JOIN cadastros_especialidades AS CadastrosEspecialidade ON (Cadastro.id = CadastrosEspecialidade.cadastro_id)
INNER JOIN Especialidades AS Especialidade ON(CadastrosEspecialidade.especialidade_id = Especialidade.id AND Especialidade.id IN(1))
INNER JOIN cadastros_facilidades AS CadastrosFacilidade ON (Cadastro.id = CadastrosFacilidade.cadastro_id)
INNER JOIN Facilidades AS Facilidade ON(CadastrosFacilidade.facilidade_id = Facilidade.id AND Facilidade.id IN(1,2))
GROUP BY Cadastro.id
HAVING COUNT(*) = 5;
I'm using the HAVING clause to try to filter the results based on the number of times it shows (meaning the number of times it has been successfully "INNER JOINED"). So in every case, the count should be equal to the number of different filters I added. So if I add 3 different "tags", the count should be 3. If I add 5 different tags, the count should be 5 and so on. It works fine for a single relation (a single pair of inner joins). When I add the other 2 relations it starts to lose control.
EDIT
Here is something that I believe is working (thanks #Tomalak for pointing out the solution with sub-queries):
SELECT Cadastro.*, Convenio.*, Especialidade.*, Facilidade.* FROM Cadastros AS Cadastro
INNER JOIN cadastros_convenios AS CadastrosConvenio ON(Cadastro.id = CadastrosConvenio.cadastro_id)
INNER JOIN Convenios AS Convenio ON (CadastrosConvenio.convenio_id = Convenio.id)
INNER JOIN cadastros_especialidades AS CadastrosEspecialidade ON (Cadastro.id = CadastrosEspecialidade.cadastro_id)
INNER JOIN Especialidades AS Especialidade ON(CadastrosEspecialidade.especialidade_id = Especialidade.id)
INNER JOIN cadastros_facilidades AS CadastrosFacilidade ON (Cadastro.id = CadastrosFacilidade.cadastro_id)
INNER JOIN Facilidades AS Facilidade ON(CadastrosFacilidade.facilidade_id = Facilidade.id)
WHERE
(SELECT COUNT(*) FROM cadastros_convenios WHERE cadastro_id = Cadastro.id AND convenio_id IN(1, 2, 3)) = 3
AND
(SELECT COUNT(*) FROM cadastros_especialidades WHERE cadastro_id = Cadastro.id AND especialidade_id IN(3)) = 1
AND
(SELECT COUNT(*) FROM cadastros_facilidades WHERE cadastro_id = Cadastro.id AND facilidade_id IN(2, 3)) = 2
GROUP BY Cadastro.id
But I'm concerned about performance. It looks like these 3 sub-queries in the WHERE clause are gonna be over-executed...
Another solution
It joins subsequent tables only if the previous joins were a success (if no rows match one of the joins, the next joins are gonna be joining an empty result-set) (thanks #DRapp for this one)
SELECT STRAIGHT_JOIN
Cadastro.*
FROM
( SELECT Qualify1.cadastro_id
from
( SELECT cc1.cadastro_id
FROM cadastros_convenios cc1
WHERE cc1.convenio_id IN (1, 2, 3)
GROUP by cc1.cadastro_id
having COUNT(*) = 3 ) Qualify1
JOIN
( SELECT ce1.cadastro_id
FROM cadastros_especialidades ce1
WHERE ce1.especialidade_id IN( 3 )
GROUP by ce1.cadastro_id
having COUNT(*) = 1 ) Qualify2
ON (Qualify1.cadastro_id = Qualify2.cadastro_id)
JOIN
( SELECT cf1.cadastro_id
FROM cadastros_facilidades cf1
WHERE cf1.facilidade_id IN (2, 3)
GROUP BY cf1.cadastro_id
having COUNT(*) = 2 ) Qualify3
ON (Qualify2.cadastro_id = Qualify3.cadastro_id) ) FullSet
JOIN Cadastros AS Cadastro
ON FullSet.cadastro_id = Cadastro.id
INNER JOIN cadastros_convenios AS CC
ON (Cadastro.id = CC.cadastro_id)
INNER JOIN Convenios AS Convenio
ON (CC.convenio_id = Convenio.id)
INNER JOIN cadastros_especialidades AS CE
ON (Cadastro.id = CE.cadastro_id)
INNER JOIN Especialidades AS Especialidade
ON (CE.especialidade_id = Especialidade.id)
INNER JOIN cadastros_facilidades AS CF
ON (Cadastro.id = CF.cadastro_id)
INNER JOIN Facilidades AS Facilidade
ON (CF.facilidade_id = Facilidade.id)
GROUP BY Cadastro.id
Emphasis mine
"It should only return the row from Cadastros if it has a matching row for EVERY "tag" provided."
"where there is a matching row"-problems are easily solved with EXISTS.
EDIT After some clarification, I see that using EXISTS is not enough. Comparing the actual row counts is necessary:
SELECT
*
FROM
Cadastros c
WHERE
(SELECT COUNT(*) FROM cadastros_facilidades WHERE cadastro_id = c.id AND id IN (2,3)) = 2
AND
(SELECT COUNT(*) FROM cadastros_especialidades WHERE cadastro_id = c.id AND id IN (1)) = 1
AND
(SELECT COUNT(*) FROM cadastros_facilidades WHERE cadastro_id = c.id AND id IN (1,2)) = 2
The indexes on the link tables should be (cadastro_id, id) for this query.
Depending on the size of the tables (records), WHERE-based subqueries, running a test on every row CAN SIGNIFICANTLY hit performance. I have restructured it which MIGHT better help, but only you would be able to confirm. The premise here is to have the first table based on getting distinct IDs that meet the criteria, join THAT set to the next qualifier criteria... joined to the FINAL set. Once that has been determined, use THAT to join to your main table and its subsequent links to get the details you are expecting. You also had an overall group by by the ID which will eliminate all other nested entries as found in the support details table.
All that said, lets take a look at this scenario. Start with the table that would be EXPECTED TO HAVE THE LOWEST RESULT SET to join to the next and next. if cadastros_convenios has IDs that match all the criteria include IDs 1-100, great, we know at MOST, we'll have 100 ids.
Now, these 100 entries are immediately JOINED to the 2nd qualifying criteria... of which, say it only matches ever other... for simplicity, we are now matched on 50 of the 100.
Finally, JOIN to the 3rd qualifier based on the 50 that qualified and you get 30 entries. So, within these 3 queries you are now filtered down to 30 entries with all the qualifying criteria handled up front. NOW, join to the Cadastros and then subsequent tables for the details based ONLY on the 30 that qualified.
Since your original query would eventually TRY EVERY "ID" for the criteria, why not pre-qualify it up front with ONE query and get just those that hit, then move on.
SELECT STRAIGHT_JOIN
Cadastro.*,
Convenio.*,
Especialidade.*,
Facilidade.*
FROM
( SELECT Qualify1.cadastro_id
from
( SELECT cc1.cadastro_id
FROM cadastros_convenios cc1
WHERE cc1.convenio_id IN (1, 2, 3)
GROUP by cc1.cadastro_id
having COUNT(*) = 3 ) Qualify1
JOIN
( SELECT ce1.cadastro_id
FROM cadastros_especialidades ce1
WHERE ce1.especialidade_id IN( 3 )
GROUP by ce1.cadastro_id
having COUNT(*) = 1 ) Qualify2
ON Qualify1.cadastro_id = Qualify2.cadastro_id
JOIN
( SELECT cf1.cadastro_id
FROM cadastros_facilidades cf1
WHERE cf1.facilidade_id IN (2, 3)
GROUP BY cf1.cadastro_id
having COUNT(*) = 2 ) Qualify3
ON Qualify2.cadastro_id = Qualify3.cadastro_id ) FullSet
JOIN Cadastros AS Cadastro
ON FullSet.Cadastro_id = Cadastro.Cadastro_id
INNER JOIN cadastros_convenios AS CC
ON Cadastro.id = CC.cadastro_id
INNER JOIN Convenios AS C
ON CC.convenio_id = C.id
INNER JOIN cadastros_especialidades AS CE
ON Cadastro.id = CE.cadastro_id
INNER JOIN Especialidades AS E
ON CE.especialidade_id = E.id
INNER JOIN cadastros_facilidades AS CF
ON Cadastro.id = CF.cadastro_id
INNER JOIN Facilidades AS F
ON CF.facilidade_id = F.id