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"
Related
I have seen several posts about this on Stack Overflow, but none of them seems to give me an answer that I can understand.
I am trying to join several relations together in order to get all of the relevant information to output all routes that start in China and end in the United States.
In the SeaRoute relation, the start_port and end_port are stored as INT and in the Port relation the pid corresponds to the start_port and end_port and includes a pcountry column.
I am starting off with just trying to output everything that has a start_port that is in China. I am expecting 3 results from my Record relation as those are the only ones that start with China in the table; However, I am receiving 6 records at the output (all of the results appear to have been doubled if I go back and audit what's in the table).
While I want the right answer, I am more concerned that I have a fundamental misunderstanding of Inner Join and the other Join methods. What am I doing wrong?
SELECT *
FROM Record
INNER JOIN Goods AS Go_data
ON Record.gid = Go_data.gid
LEFT JOIN SeaRoute AS SR
ON Record.rid = SR.rid
RIGHT JOIN (SELECT pid, pcountry AS starting_port_country
FROM Port
INNER JOIN SeaRoute AS SR ON Port.pid = SR.start_port
WHERE Port.pcountry = 'China')
AS start_port_table ON SR.start_port = start_port_table.pid
From the looks of your query, you want to be INNER JOINing between the records that you have only on the routes that you want.
You know all of the SeaRoutes that start in China and end in the United States already, you do however need to join to the Ports table twice like so:
SELECT sr.rid,
sp.pcountry AS starting_port_country,
ep.pcountry AS end_port_country
FROM dbo.SeaRoute sr
INNER JOIN dbo.Port sp ON sp.pid = sr.start_port
INNER JOIN dbo.Port ep ON ep.pid = sr.end_port
WHERE sp.pcountry = 'China'
AND ep.pcountry = 'United States'
Then you just need to join that to your main query:
SELECT *
FROM Record
INNER JOIN dbo.Goods AS Go_data ON Record.gid = Go_data.gid
INNER JOIN
(
SELECT sr.rid,
sp.pcountry AS starting_port_country,
ep.pcountry AS end_port_country
FROM dbo.SeaRoute sr
INNER JOIN dbo.Port sp ON sp.pid = sr.start_port
INNER JOIN dbo.Port ep ON ep.pid = sr.end_port
WHERE sp.pcountry = 'China'
AND ep.pcountry = 'United States'
) ports ON ports.rid = Record.rid
There's no way I can explain joins to you any clearer than this page can:
https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-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
I have a table for audit trail which saves all actions performed records through out the project like add update and delete.
there I maintain a column which saves primary keys of multiple tables on which action is performed. This is integer column
my query is like this
select * from
user usr1
left join activity_history
on activity_history.userID= usr1.sequenceID
left join candidate can1 on can1.userID = usr1.sequenceID
and can1.userID = activity_history.activity_sequenceID
left join institute ins1 on ins1.userID= usr1.sequenceID
and ins1.userID = activity_history.activity_sequenceID
left join candidate_institutes caninst on caninst.candidateID = can1.candidateID and caninst.instituteID= ins1.instituteID
left join exam exam1 on exam1.instituteID = ins1.instituteID
and exam1.examID = activity_history.activity_sequenceID
left join proctor pro1 on pro1.userID = usr1.sequenceID
and pro1.proctorID = activity_history.activity_sequenceID
left join appointment appt1 on appt1.examID = exam1.examID
and appt1.sequenceID = activity_history.activity_sequenceID
/* COMMENTED CODE-----
on( activity_history.activity_sequenceID=can1.userID
OR activity_history.activity_sequenceID=ins1.userID
OR activity_history.activity_sequenceID=exam1.examID and activity_history.userID= usr1.sequenceID
OR activity_history.activity_sequenceID=pro1.userID
OR activity_history.activity_sequenceID=appt1.sequenceID
)
*/
order by activity_history.sequenceID desc
activity_sequenceID is the column where I am storing keys of other tables
I need to map that. Is this a right way to join these tables or Commented part could be the rite way ?
Or is there any other way to join these tables.
I am confused because I am writing a condition in but activity_histry table may or may not have records of that particular table .
A bit of a newbie question, probably an INNER JOIN with an "AS" statement, but I can't figure it out...
This is for a MYSQL based competition app. I want to select the "img_title" for both img_id1 and img_id2. I can't figure out how to do it and still see which title is assigned to the associated _id1 or _id2.
My tables:
competitions
comp_id
img_id1
img_id2
on_deck
img_id
img_title
Desired results:
comp_id | img_id1 | img_title1 |img_id2 | img_title2
You need a join for each image:
SELECT comp.comp_id, img1.img_id, img1.img_title, img2.img_id, img2.img_title
FROM competitions comp
INNER JOIN on_deck img1 ON img1.img_id = comp.img_id1
INNER JOIN on_deck img2 ON img2.img_id = comp.img_id2
LEFT JOIN if img_id1 or img_id2 can be NULL.
select comp_id, img_id1, b.img_title as img_title1,
img_id2, b2.img_title as img_title2
from competitions a
left outer join on_deck b on b.img_id = a.img_id1
left outer join on_deck b2 on b2.img_id = a.img_id2
switch let outer join to inner join if you want to exclude rows in competitions that do not have two matching img_ids
This query should give you the results you want. This also assumes that comp.img_id1 and comp.img_id2 are never NULL.
SELECT comp.comp_id
, comp.img_id1
, deck1.img_title AS img_title1
, comp.img_id2
, deck2.img_title AS img_title2
FROM competitions AS comp
JOIN on_deck deck1 ON comp.img_id1 = deck1.img_id
JOIN on_deck deck2 ON comp.img_id2 = deck2.img_id
If you have plan on having a NULL or empty string comp.img_id1 and/or comp.img_id2 fields, you'll need to do some left joins.
If someone could offer advice on improving the below query this would be most useful. I am unsure how I can make improvement when i have a left join twice in many instance to seperate tables. For example I have a location left join to the user table and a location left join to the image gallery table. I was unsure if i could optimise the sql from this point of view. It is very slow at the moment. I have ensured all columns are indexed on all joins and where statements.
SELECT im.alias_title, im.title,im.guid_id, im.description, im.hits, im.show_comment, im.can_print,
im.can_download, im.can_share, im.created_on, im.date_taken, im.approved, im.visible,
ad.address_line_1, ad.address_line_2, ad.town_village_city, ad.state_province_county, ad.postal_code, ad.other_address_detail, co.country,
geo.latitude, geo.longitude, geo.zoom, geo.yaw, geo.pitch,
c.make, c.model,
us.first_name, us.surname, uf.user_id, uf.real_name, uf.user_name, uf.gender, uf.description, uf.description, uf.buddy_icon_url, uf.first_taken_date, uf.first_date,
uf.time_zone_label, uf.time_zone_offset,
adf.address_line_1 as user_address_line_1, adf.address_line_2 as user_address_line_2, adf.town_village_city as user_town_village_city, adf.state_province_county as user_state_province_county,
adf.postal_code as user_postal_code, adf.other_address_detail as user_other_address_detail, cof.country as user_country,
geof.latitude as user_geolocation_latitude, geof.longitude as user_geolocation_longitude, geof.zoom as user_geolocation_zoom, geof.yaw as user_geolocation_yaw, geof.pitch as user_geolocation_pitch,
im.alias_title = in_image_alias_title AS image_selected -- image selected
FROM image im
LEFT JOIN address ad ON im.address_id = ad.id
LEFT JOIN country co ON ad.country_id = co.id
LEFT JOIN geolocation geo ON im.geolocation_id = geo.id
LEFT JOIN camera c ON im.camera_id = c.id
INNER JOIN user us ON im.user_id = us.id
LEFT JOIN user_flickr uf ON us.id = uf.id
LEFT JOIN address adf ON uf.address_id =adf.id
LEFT JOIN country cof ON ad.country_id = cof.id
LEFT JOIN geolocation geof ON uf.geolocation_id = geof.id
WHERE (im.alias_title = in_image_alias_title OR im.user_id = user_id)
AND im.approved = in_image_approved
AND im.visible = in_image_visible
AND (im.advertise_to <= NOW() OR im.advertise_to IS NULL)
ORDER BY image_selected DESC;
After the discussion / chat room, and learning more of what you were trying to do...
Build a compound index on the components associated with your where clause so all parts can be applied, not just the best of the first key element. Also, by removing the "alias_title" from the where clause (since you were getting the user ID based on the alias title to begin with), it was a redundant clause taking up more consideration in the query.
I would index on (user_id, approved, visible, advertise_to )
The results will come back and be small in the scheme of things, so your ultimate "order by" clause will have no problem with its final sort output.