Getting team names when given two team IDs - sql-server

I need to get a Select query that lets me display team names instead of IDs.
I store information about teams(ID, Name); match(ID, ht_ID(FK to teams(ID), at_ID(FK to teams(ID)); match_results(ID, Match_ID(FK to match(ID), Results(varchar)) each in seperate table as shown above.
For example, if I do -
select match.ID, match.ht_ID, match.at_ID, match_results.Results from match_results
join match on mattch.ID = match_results.Match_ID
This query is going to output ID, Home team id, Away team ID and the score. How can I write the query so I can see the team names instead of team ids? Thanks!

You need to join twice onto your teams table using a different alias each time
select match.ID, match.ht_ID, ht.Name as ht_Name, match.at_ID, at.Name as at_Name, match_results.Results
from match_results
join match on mattch.ID = match_results.Match_ID
join teams ht on match.ht_ID = ht.ID
join teams at on mtach.at_ID = at.ID

You should use aliases for the table names and the selected fields as well to be able track and pick columns for the stated tables and advise you use left you get specific rows.
SELECT DISTINCT mr.name as match_results, ht.name as home_team,at.name as
away_team FROM match_results mr LEFT JOIN match m ON mr.match_id = m.id
LEFT JOIN teams ht m.ht_id = ht.id LEFT JOIN teams at m.at_id = at.id;

Related

How can I get 3 tables INNER JOIN in MS SQL Server

From the specialist table, retrieve the first name, last name and contact number for the people that provide care to penguins from the species table.
There are 3 tables: tbl_specialist, tbl_species, tbl_care
I need help trying to INNER JOIN the tables to display First, Last, And Contact for penguins.
SELECT specialist_fname, specialist_lname, specialist_contact
FROM ((tbl_specialist
INNER JOIN tbl_species ON species_care = tbl_species.species_care)
INNER JOIN tbl_care ON care_id = tbl_care.care_id)
WHERE species_name = 'penguin'
;
It's a bit difficult without seeing the exact schema of the tables, but your syntax for the subquery is a bit off and you need to alias columns that are found in multiple tables in a JOIN statment. Try rewriting your SQL like this:
SELECT spl.specialist_fname, spl.specialist_lname, spl.specialist_contact
FROM tbl_specialist spl
INNER JOIN tbl_species s
ON spl.species_care = s.species_care
INNER JOIN tbl_care c
ON s.care_id = c.care_id
WHERE s.species_name = 'penguin'
I'm obviously inferring which tables certain columns come from in the join, but hopefully you get the idea.
I figured it out thank you.
SELECT specialist_fname, specialist_lname, specialist_contact
FROM ((tbl_specialist
INNER JOIN tbl_care ON tbl_care.care_specialist = tbl_specialist.specialist_id)
INNER JOIN tbl_species ON tbl_species.species_care= tbl_care.care_id)
WHERE species_name = 'penguin'
;

How do I query three related tables?

I'm new to databases and I'm having a hard time figuring this out. Any assistance would be greatly appreciated
Deliveries Table
-- ID (PK)
-- DriverID (FK to Drivers Table)
Drivers Table
-- ID (PK)
-- LocationID (FK to Locations Table)
Locations Table
-- ID (PK)
-- RestaurantID (FK to Restaurants Table)
Restaurant Table
--ID (PK)
A Restaurant can have multiple locations (1 to many). A location can have multiple drivers (1 to many). a Driver can have multiple deliveries (1 to many). This design is supposed to break things out in 3rd normal form. So if I want to go to the deliveries table and get all of the deliveries associated with a particular restaurant, how would I query or do a join for that? Would I have to add a second foreign key to Deliveries that directly references the Restaurant table? I think after I see the query I can figure out what is going on. Thx
You can use left or right outer join to make a combined table and then you can easily query it, or else you can use a query with multiple sub-queries inside it to attain the required result without using join. Here is an example on how to use sub-query for your use-case.
SELECT ID FROM Deliveries De
WHERE De."DriverID" IN (SELECT ID FROM Drivers Dr
WHERE Dr. "LocationID" IN (SELECT ID FROM Locations L
WHERE L. "RestaurantID" IN (SELECT ID FROM Restaurant)))
I hope this solves your issue without using join statement.
You can use inner join or union depending on what you want to achieve. Example:
SELECT a."articleId" AS id, a.title, a."articleImage" AS "articleImage/url", c.category AS "category/public_id", a."createdOn", concat("firstName", ' ', "lastName") AS author
FROM articles a
INNER JOIN users u ON a."userId" = u."userId"
INNER JOIN categories c ON a."categoryId" = c."categoryId"
UNION
SELECT g."gifId" AS id, g.title, g."imageUrl" AS "articleImage/url", g.public_id AS "category/public_id", g."createdOn", concat("firstName", ' ', "lastName") AS author
FROM gifs g
INNER JOIN users u ON g."userId" = u."userId"
ORDER BY "createdOn" DESC
You can say how you want to get the results for more detailed query.
If I understand what you want to do then it maybe like this,
1st you have to join all those table to get corresponding result you want,
the join condition will be
select <your desire column name>
from Restaurant A,Locations B,Drivers C,Deliveries D
where A.ID = B.RestaurantID
and B.ID = C.LocationID
and C.ID = D.DriverID
Hope this is helpful, fell free to say anything.

How to create an association with the last record of an other table

I'm working on an application for iceskaters with cakephp. A part of my database shema is like this :
Nations-(1,n)-Skaters-(1,n)-Participations-(n,1)-Competitions
Participations has a rank field and Competitions has a date field
I want to have an hasOne association from Skaters to the last Participation (of this skater) according to the date field in the table Competitions. I need that in model because i want to order Skaters by the last Participation or by the rank obtained during the last participation.
I don't know if it is possible with cakephp v3.x
In MySQL i write a query that seems to works :
Select s.id, c.title, c.date, p.id, p.rank
from
(
SELECT skater_id, max(competitions.date) as maxdate
FROM `participations`
inner join competitions on competitions.id = participations.competition_id
group by skater_id
) as x
inner join participations as p on p.skater_id = x.skater_id
inner join competitions as c on c.id = p.competition_id
inner join skaters as s on x.skater_id = s.id and maxdate = c.date
I've found a very usefull post but i'm not able to adapt it to my case (filtering field in third table not second one). The only result was : An Internal Server Error Occurred. So too dificult for me to debug without information.
Regards

Need query to determine number of attachments for each issue

I have a database in SQL Server that has three tables: Issues, Attachments, and Requestors. I need a single query that returns all the columns contained in the "Issues" and "Attachments" tables. Listed below is the query that I've created, but it's not working as expected:
SELECT A.*,
B.*,
SubQuery.attachmentcount
FROM [DB].[dbo].[issues] AS A
FULL OUTER JOIN [DB].[dbo].[requestors] AS B
ON A.issue_id = B.issue_id,
(SELECT Count(attachments.attachment_id) AS AttachmentCount
FROM issues
LEFT OUTER JOIN attachments
ON issues.issue_id = attachments.issue_id
WHERE attachments.attachment_status = 1
GROUP BY issues.issue_id) AS SubQuery;
Pictures describing the three tables are listed below:
Any ideas on how to fix my query?
Thanks,
"I need a single query that returns all the columns contained in the "Issues" and "Attachments" tables".
Based on this sentence try this:
SELECT A.Issue_ID, I.Issue_Name,r.Name, COUNT(A.attachment_id) AS Count
FROM Attachments as A
INNER JOIN Issues I on I.issue_id = A.issue_id
INNER JOIN requestors as R on A.issue_id = R.requestor_id
WHERE A.attachment_status = 1
GROUP BY A.Issue_ID, I.Issue_Name, r.Name
--Specify all columns by name (don't use *)
Keep It Simple and Try This!
SELECT i.Issue_ID, i.Issue_Name, COUNT(a.attachment_id) AS AttachmentCount
FROM attachments a JOIN
issues i ON
i.issue_id = a.issue_id
WHERE a.attachment_status = 1
GROUP BY i.Issue_ID, i.Issue_Name
Add your Desired Columns in Both Select List and Group By Clause and you are done.

Select value from different tables based on the column value in SQL Server

I have a main table A with the following fields:
Then I have three separate tables, each for Buildings, Classrooms and Offices. All these tables have two columns; ID and Name.
I want to query the table A to get the following result:
How can I do this?
Your data isn't really normalized. Having three separate tables all serving the same lookup is causing you some headache... so I unioned the 3 tables together and created a 'src' column so you could join table A's type and Id back to table B's ID and src. You'd have been better off having one table and non-repeating IDs and a type ID to specify if it's a building classroom or office.
Select *
from A
LEFT JOIN (SELECT 'Building' as src, ID, Name FROM Buildings UNION ALL
SELECT 'Classroom' as src, ID, Name FROM Classrooms UNION ALL
SELECT 'Office' as src, ID, Name FROM Offices) B
on A.Location_Type = B.Src
and A.LocationID = B.ID
I used a left join here in case not all records in A have an associated record in B. However, an inner join should work as well.
Should be doable with the use of a join.
Something along those lines should work:
SELECT tabelA.ID, tabelA.Subject, tabelA.Date, tabelA.locationType, tabelB.location
FROM tabelA INNER JOIN tabelB on tabelA.locationID = tabelB.locationID

Resources