Double query a table from two fields (INNER JOIN?) - mysql

I hope I can explain myself.
I have a many to many table (asignaciones) which points to alumnos and invest tables. Both of those tables has a institucionID which points to instituciones table.
I need to get (in one query) both instituciones from alumnos and invest. I have this but is not complete. I guess if because of the AND in the last inner join:
SELECT
alumnos.alumnosID,
invest.investigadoresID,
asignaciones.alumnosID AS alumnosID1,
asignaciones.investigadoresID AS investigadoresID1,
instituciones.institucion
FROM alumnos
INNER JOIN asignaciones ON alumnos.alumnosID = asignaciones.alumnosID
INNER JOIN invest ON asignaciones.investigadoresID = invest.investigadoresID
INNER JOIN instituciones ON alumnos.institucionesID = instituciones.institucionesID AND invest.institucionesID = instituciones.institucionesID
This lacks the second institucion. I am getting just one
Any hints on this is really appreciated

This Query schold solve your problem:
SELECT
alumnos.alumnosID,
invest.investigadoresID,
asignaciones.alumnosID AS alumnosID1,
asignaciones.investigadoresID AS investigadoresID1,
instituciones.institucion
instituciones1.institucion
FROM alumnos
INNER JOIN asignaciones ON alumnos.alumnosID = asignaciones.alumnosID
INNER JOIN invest ON asignaciones.investigadoresID = invest.investigadoresID
INNER JOIN instituciones instituciones ON alumnos.institucionesID = instituciones.institucionesID
INNER JOIN instituciones instituciones1 ON invest.institucionesID = instituciones1.institucionesID
You have to join the last table twice.

Related

Join 4 tables with specified column

I have this code:
SELECT A.UNITCODE, B.FORMATIONCODE, C.UPPERFORMATIONCODE, D.UPPERFORMATIONCODE
FROM UNIT AS A.UNITCODE
INNER JOIN FORMATION AS B.FORMATIONCODE
INNER JOIN UPPERFORMATION_UNIT AS C.UPPERFORMATION
INNER JOIN UPPERFORMATION AS D.UPPERFORMATIONCODE
WHERE UNITCODE='7000007'
Can you guys help me how to join 4 tables with specified column?
Assuiming the all 3 related tables have the same UNIT_ID for join with table UNIT
SELECT
A.UNITCODE
, B.FORMATIONCODE
, C.UPPERFORMATIONCODE
, D.UPPERFORMATIONCODE
FROM UNIT AS A
INNER JOIN FORMATION AS B ON B.FORMATIONCODE = A.UNIT_ID
INNER JOIN UPPERFORMATION_UNIT AS C. C.UPPERFORMATION = A.UNIT_ID
INNER JOIN UPPERFORMATION AS D D.UPPERFORMATIONCODE = A.UNIT_ID
WHERE UNITCODE='7000007'
It seems you are confusing table aliases and linking columns.
This is how to give a table an alias name in the query in order to enhance readability:
INNER JOIN formation AS f
where the AS is optional. Most often it is ommited.
This is how to join:
FROM unit AS u
INNER JOIN upperformation_unit AS ufu ON ufu.unitcode = u.unitcode
Well, I don't know the columns linking the tables of course, let alone their names. But I suppose the query would have to look like this more or less:
SELECT
u.unitcode,
f.formationcode,
uf.upperformationcode,
ufu.upperformationcode
FROM unit u
JOIN upperformation_unit ufu ON ufu.unitcode = u.unitcode
JOIN upperformation uf ON uf.upperformationcode = ufu.upperformationcode
JOIN formation f ON f.formationcode uf.formationcode
WHERE u.unitcode = 7000007;

use multiple results of a query within the query with joins

I have some tables in my database, three main ones and one that holds the many-to-many relations.
1. Student (student_id, student_name)
2. Sport (sport_id, sport_name)
3. Departm (depart_id, depart_name)
4. Sch (sch_id, sch_name)
5. StudSport(relationid, studendid, sportid, departid, schid)
What I want to do is e.g. retrieve the name of the department based on the relations when I know the id. I can get the ids like this:
SELECT departid, schid from studsport
inner join Student on student_id = studentid
inner join Sport on sport_id = sportid
where student_id = 1 and sport_id=2
but I want to get the names of the department and the Sch from their corresponding tables, and I dont know how to do that.
As you don't select anything from Student or Sport, you can remove the corresponding inner joins.
SELECT d.depart_name, sch.sch_name FROM StudSport s
INNER JOIN Sch sch ON s.schid = sch.sch_id
INNER JOIN Departm d ON s.departid = d.depart_id
WHERE s.studendid = 1 AND s.sportid = 2
Something like this???
select sch.sch_nam, departm.depart_name,
-- what you have already --
Left outer Join StudSport on Student.student_id = Studsport.studentid and Sport.sport_id = StudSport.sportid
left outer Join Sch on StudSport.schid = Sch.sch_id
left outer join Departm on studsport.depart_id = studsport.departid
This is untested, a fiddle makes it much easier to give answers because of that.
EDIT - I misread your original query - before the downvotes start to rain - fixing it right now.
The way you should use LEFT OUTER and INNER joins is how the data is meant (again, a fiddle will normally be usefull) but it's just a couple of joins from what you have i guess:
select *
from studsport
join student on studsport.studentid = student.student_id
join sport on studsport.sportid = sport.sport_id
left outer Join Sch on StudSport.schid = Sch.sch_id
left outer join Departm on studsport.depart_id = studsport.departid
where student_id = 1 and sport_id=2

SQL Join for Five Tables

I am actually trying to Join Five Tables in MySQL Database based upon RegionID which is a unique key present in all tables. I am new to it and using the following left join statement:
SELECT `tbllistings`.*,
`tblgallery`.*,
`tbltowns`.*,
`tblregions`.*,
`tblcontent`.*,
`tbllistings`.*,
`tblgallery`.*,
`tbltowns`.*,
`tblregions`.*,
`tblcontent`.*
FROM tbllistings
LEFT JOIN `webspace_db`.`tblregions`
ON `tbllistings`.`intregionid` = `tblregions`.`intregionid`
LEFT JOIN `webspace_db`.`tblcontent`
ON `tblregions`.`intregionid` = `tblcontent`.`intregionid`
LEFT JOIN `webspace_db`.`tblgallery`
ON `tblregions`.`intregionid` = `tblgallery`.`regionid`
LEFT JOIN `webspace_db`.`tbltowns`
ON `tblregions`.`intregionid` = `tbltowns`.`intregionid`
The problem that I am facing is each value is showing up more then 20+ times and I am unsure why is this happening. What I actually want is to simply join all fields from all tables based on RegionID.
Any help and suggestions are highly welcomed. Thanks a lot.
Use tbllistings.intregionid in every ON clause.
SELECT `tbllistings`.*,
`tblgallery`.*,
`tbltowns`.*,
`tblregions`.*,
`tblcontent`.*,
`tbllistings`.*,
`tblgallery`.*,
`tbltowns`.*,
`tblregions`.*,
`tblcontent`.*
FROM tbllistings
LEFT JOIN `webspace_db`.`tblregions`
ON `tblregions`.`intregionid` = `tbllistings`.`intregionid`
LEFT JOIN `webspace_db`.`tblcontent`
ON `tblcontent`.`intregionid` = `tbllistings`.`intregionid`
LEFT JOIN `webspace_db`.`tblgallery`
ON `tblgallery`.`regionid` = `tbllistings`.`intregionid`
LEFT JOIN `webspace_db`.`tbltowns`
ON `tbltowns`.`intregionid` = `tbllistings`.`intregionid`

Need some assistance with a complex JOIN is SQL Query

Take a look at these tables
It's simple: Venue contains country_ID which is an FK in Society_Territory where we will find a society_ID which is an FK of Society. I have a Venue_ID during the query and my objective is to get the Society_Name but there is a twist but first lets just get the Society_Name
In the following query only look at JOINS and in there I am gonna add comments with this // prefix
SELECT
uuid()AS `UUID`,
`pc`.`PRSClaimID` AS `prsclaimid`,
`a`.`LoginName` AS `loginname`,
`a`.`BandName` AS `bandname`,
`smartistdetails`.`LoginName` AS `createdbyloginname`,
`Society`.`Society_Name` AS societyName
count(
`smliveclaims`.`LiveclaimsID`
)AS `gigcount`
FROM `smprsliveclaimlink`
JOIN `smliveclaims` ON `smprsliveclaimlink`.`fkLiveClaimID` = `smliveclaims`.`LiveclaimsID`
// Here I have the Venue_ID from smliveclaims so i starting moving towards society name
JOIN Venue ON `smliveclaims`.fk_venueId = Venue.Venue_ID
JOIN Society_Territory ON Venue.Country_ID = Society_Territory.Country_ID
JOIN Society ON Society_Territory.Society_Id = Society.Society_ID
// Now from Society i can select the Society_Name which i am already doing in the query above
JOIN `smartistdetails` `a`
JOIN `smprsclaims` `pc` ON `a`.`ArtistID` = `pc`.`fkArtistID`
JOIN `smcategories` ON `pc`.`FK_CategoryID` = `smcategories`.`Id`
JOIN `smcategoriestype` ON `smcategories`.`fk_CategoryTypeId` = `smcategoriestype`.`Id`
JOIN `smartistdetails` ON `pc`.`CreatedBy` = `smartistdetails`.`ArtistID` AND `smprsliveclaimlink`.`fkPRSClaimID` = `pc`.`PRSClaimID`
GROUP BY
`a`.`LoginName`,
`a`.`BandName`,
`smcategories`.`Id`,
`smcategoriestype`.`CategoryType`,
`smartistdetails`.`LoginName`
All is cool till here. Now here is the TWIST
I will have Country_IDs in Venue which will not be in Society_Territory. And I still want to select them and instead of showing and actual Society_Name want to show a word such as "Other"
use a LEFT OUTER JOIN when you link VENUE with SOCIETY_TERRITORY and so on when you link SOCIETY_TERRITORY with SOCIETY
Pay attention: When you use a LEFT OUTER JOIN all tables depends by its must be linked with other LEFT OUTER JOIN because if you use INNER JOIN you cancel di effects on LEFT.
Edit:
SELECT
uuid()AS `UUID`,
`pc`.`PRSClaimID` AS `prsclaimid`,
`a`.`LoginName` AS `loginname`,
`a`.`BandName` AS `bandname`,
`smartistdetails`.`LoginName` AS `createdbyloginname`,
coalesce(`Society`.`Society_Name`, 'Other') AS societyName
count(`smliveclaims`.`LiveclaimsID`)AS `gigcount`
FROM `smprsliveclaimlink`
JOIN `smliveclaims`
ON `smprsliveclaimlink`.`fkLiveClaimID` = `smliveclaims`.`LiveclaimsID`
// Here I have the Venue_ID from smliveclaims so i starting moving towards society name
JOIN Venue ON `smliveclaims`.fk_venueId = Venue.Venue_ID
LEFT OUTER JOIN Society_Territory ON Venue.Country_ID = Society_Territory.Country_ID
LEFT OUTER JOIN Society ON Society_Territory.Society_Id = Society.Society_ID
// Now from Society i can select the Society_Name which i am already doing in the query above
JOIN `smartistdetails` `a`
JOIN `smprsclaims` `pc` ON `a`.`ArtistID` = `pc`.`fkArtistID`
JOIN `smcategories` ON `pc`.`FK_CategoryID` = `smcategories`.`Id`
JOIN `smcategoriestype` ON `smcategories`.`fk_CategoryTypeId` = `smcategoriestype`.`Id`
JOIN `smartistdetails` ON `pc`.`CreatedBy` = `smartistdetails`.`ArtistID` AND `smprsliveclaimlink`.`fkPRSClaimID` = `pc`.`PRSClaimID`
GROUP BY
`a`.`LoginName`,
`a`.`BandName`,
`smcategories`.`Id`,
`smcategoriestype`.`CategoryType`,
`smartistdetails`.`LoginName`
All your JOINs are INNER JOINs. The INNER keyword is optional in MySQL and frequently omitted (as in your example). Use a LEFT OUTER JOIN where required and amend your SELECT clause to include something like "COALESCE(Society_Name,'Other') Society_Name"

mysql: fast group by with join

I have this query with many left joins and a inner join with dates.
I need to group by id_art (from articles_art) and date_dat (dates_dat). The problem is that is really slow. it takes 3second for 1000records.
dates_dat is indexed in dates_dat table and id_art is a primary key of articles_art.
What can I do to optimize this query?
SELECT
id_art, image2_art, video_art, website,
text.title_int, text.intro_int, text.text_int, text.extra_int,
dat.date_dat, dat.date2_dat,
group_concat(tim.time_tim),
prd.name_prd,
group_concat(cat.name_cat),
trg.name_trg,
spa.name_spa,
spa2.name_spa
FROM
articles_art AS art
LEFT JOIN internText_int AS text ON text.idart_int = art.id_art
INNER JOIN dates_dat AS dat ON art.id_art = dat.idart_dat
LEFT JOIN spaces_spa As spa ON spa.id_spa = dat.idspa_dat
LEFT JOIN spaces_spa As spa2 ON spa.id_spa = dat.idspa2_dat
LEFT JOIN times_tim AS tim ON tim.iddat_tim = dat.id_dat
LEFT JOIN articles_products_artprd AS artprd ON artprd.idart_artprd = art.id_art
LEFT JOIN products_prd AS prd ON prd.id_prd = artprd.idprd_artprd
LEFT JOIN cater_cev AS cev ON cev.idart_cev = dat.idart_dat
LEFT JOIN categories_cat AS cat ON cat.id_cat = cev.idcat_cev
LEFT JOIN targets_trg AS trg ON trg.id_trg = art.idtrg_art
WHERE
prd.id_prd in (1,2)
AND validated_art = 1
AND text.idlin_int in (1,4)
GROUP BY
id_art, date_dat
Look like you can put an index on these columns
prd.id_prd
validated_art
text.idlin_int
Test this first then if this does not work put indexes on column conditions on the ON clause
If data latency isn't an issue, can you hive the data off (perhaps overnight?) into a single normalised table? That way you query a single table without all those JOINS. You could even apply indexes to help speed things up further.