SQL Join tables (multiple number of id's) - sql

I have two tables:
The first one (players) contains player records with it ID's and names.
Another one (results) contains results:
ID of 1 player against ID of 2 player
How can I select their names?
SELECT *
FROM results
ORDER by result_date DESC
It looks like this for now. I want to have instead of numbers real player names.

You just need to set two different alias for the players table:
select *
from results
join players as pair1players on results.Pair1 = pair1players.ID
join players as pair2players on results.Pair2 = pair2players.ID
order by result_date desc
Here, supposing Pair1 is the name of the field "Pair #1" you showed in the screenshot, and Pair2 is the name of the field "Pair #2".

This could help:
SELECT players.ID, players.Name
FROM players
INNER JOIN results ON players.ID=results.playersID

Related

substituting ID for value

I have two tables, one is Players and second one is Participant's List. I keep full data about player only in Players table and i want to display Participant's data but i don't want to show ID, which are stored in this table. I want to replace them with data relevant to stored ID. So i wrote script:
SELECT pl.surname as Name FROM players pl, participants_list p
WHERE pl.player_id = p.player_id
And it works, but it replaces only one value which is the name of player. I need to replace also name of the tournament from other table. I don't know how to combine those two operations, which may result in getting 2 columns replaced with value. For example
Smith | Tournament 1
Kowalsky | Tournament 2
The data I have is:
Players Table
Player's id|Player's Name| and more
Events Table
Event's id|Event's Name| and more
Participant's Table
Player's id|Event's id
Try this out:
select b.player_name,c.event_name
from
Participants_table a
left join
players table b
on a.player_id = b.player_id
left join
events_table c
on a.event_id = c.event_id;
Let me know in case of any queries.

Doing a FULL OUTER JOIN in Sqlite3 to get the combination of two columns?

I'm currently working on a database project and one of the problems calls for the following:
The Genre table contains twenty-five entries. The MediaType table contains 5
entries. Write a single SQL query to generate a table with three columns and 125
rows. One column should contain the list of MediaType names; one column
should contain the list of Genre names; the third column should contain a count of
the number of tracks that have each combination of media type and genre. For
example, one row will be: “Rock MPEG Audio File xxx” where xxx is the
number of MPEG Rock tracks, even if the value is 0.
Recognizing this, I believe I'll need to use a FULL OUTER JOIN, which Sqlite3 doesn't support. The part that is confusing me is generating the column with the combination. Below, I've attached the two methods I've tried.
create view T as
select MediaTypeId, M.Name as MName, GenreId, G.Name as GName
from MediaType M, Genre G
SELECT DISTINCT GName, MName, COUNT(*) FROM (
SELECT *
FROM T
OUTER LEFT JOIN MediaType
ON MName = GName
UNION ALL
SELECT *
FROM Genre
OUTER LEFT JOIN T
) GROUP BY GName, MName;
However, that returned nearly 250 rows and the GROUP BY or JOIN(s) is totally wrong.
I've also tried:
SELECT Genre.Name as GenreName, MediaTypeName, COUNT(*)
FROM Genre LEFT OUTER JOIN (
SELECT MediaType.Name as MediaTypeName, Track.Name as TrackName
FROM MediaType LEFT OUTER JOIN Track) GROUP BY GenreName, MediaTypeName;
Which returned 125 rows but they all had the same count of 3503 which leads me to believe the GROUP BY is wrong.
Also, here is a schema of the database:
https://www.dropbox.com/s/onnbwqfrfc82r1t/IMG_2429.png?dl=0
You don't use full outer join to solve this problem.
Because it looks like a homework problem, I'll describe the solution.
First, you want to generate all combinations of genres and media types. Hint: This uses a cross join.
Second, you want to count all the combinations that you have. Hint: this uses an aggregation.
Third, you want to combine these together. Hint: left join.

Select average rating from another datatable

I have 3 data tables.
In the entries data table I have entries with ID (entryId as primary key).
I have another table called EntryUsersRatings in there are multiple entries that have entryId field and a rating value (from 1 to 5).
(ratings are stored multiple times for one entryId).
Columns: ratingId (primary key), entryId, rating (integer value).
In the third data table I have translations of entries in the first table (with entryId, languageId and title - translation).
What I would like to do is select all entries from first data table with their titles (by language ID).
On a top of that I want average rating of each entry (which can be stored multiple times) that is stored in EntryUsersRatings.
I have tried this:
SELECT entries.entryId, EntryTranslations.title, AVG(EntryUsersRatings.rating) AS AverageRating
FROM entries
LEFT OUTER JOIN
EntryTranslations ON entries.entryId = EntryTranslations.entryId AND EntryTranslations.languageId = 1
LEFT OUTER JOIN
EntryUsersRatings ON entries.entryId = EntryUsersRatings.entryId
WHERE entries.isDraft=0
GROUP BY title, entries.entryId
isDraft is just something that means that entries are not stored with all information needed (just incomplete data - irrelevant for our case here).
Any help would be greatly appreciated.
EDIT: my solution gives me null values for rating.
Edit1: this query is working perfectly OK, I was looking into wrong database.
We also came to another solution, which gives us the same result (I hope someone will find this useful):
SELECT entries.entryId, COALESCE(x.EntryUsersRatings, 0) as averageRating
FROM entries
LEFT JOIN(
SELECT rr.entryId, AVG(rating) AS entryRating
FROM EntryUsersRatings rr
GROUP BY rr.entryId) x ON x.entryId = entries.entryId
#CyberHawk: as you are using left outer join with entries, your result will give all records from left table and matching record with your join condition from right table. but for unmatching records it will give you a null value .
check out following link for the deta:
http://msdn.microsoft.com/en-us/library/ms187518(v=sql.105).aspx

How do I get unique records and ordering on outer join with 3 tables?

I have a problem with getting some ordering of records and uniqueness. I have the following setup of tables:
person
groups
group_has_person
The idea here is to sort persons into groups. (think of Google+ circles)
First I had only a person table with 2 ID fields linking to the group records but then I was always limited to having a person only in 2 groups. Now I have added a linking table so the person can be placed into an unlimited amount of groups. Every group has a sort index field (group.order_index). This is an integer defining the sort-order of the groups. The idea is to show all persons grouped by group and showing every person only once but also order not by name or id but but by the extra index field of the group. So actually I want to show all persons even when they're not in a group. But when they are in one or more groups I want to show them in the order of the group.order_index and only once.
The query result should look like this:
person.name person.person_id group.group_id group.order_index
Rick 1 1 1
Tom 2 1 1
Jan 4 3 2
Kees 3 3 2
Piet 5 NULL NULL
Notice that the group_id is not the column to order by but that table has an extra field so the order can be changed after creation of a group.
I got some queries that got close to my expected result but I'm not there yet:
This following query gives the expected sort result but it still gives a person multiple times when it is in multiple groups:
SELECT
person.person_id AS 'person.person_id',
person.name AS 'person.name',
group.order_index AS 'group.order_index',
FROM
`person`
LEFT OUTER JOIN `group_has_person` ON person.person_id = group_has_person.person_id
LEFT OUTER JOIN `group` ON group_has_person.group_id = group.group_id
ORDER BY
3 ASC ,
2 ASC
The key-word DISTINCT didn't help either.
The following query gives unique persons but the order by group_order_index doesn't work and even shows faulty numbers:
SELECT
person.person_id AS 'person.person_id',
person.name AS 'person.name',
group.order_index AS 'group.order_index',
FROM
`person`
LEFT OUTER JOIN `group_has_person` ON person.person_id = group_has_person.person_id
LEFT OUTER JOIN `group` ON group_has_person.group_id = group.workgroup_id
GROUP BY
group_has_person.person_id
ORDER BY
3 ASC ,
2 ASC
Also grouping by person.person_id doesn't help getting the right order.
Inner joins also don't work because they wont show persons that are not in a group. Is it possible to get what I want without code and only by a query without having sub-selects?
You are almost there, but you need an aggregate function on order_index:
SELECT
person.person_id AS 'person.person_id',
person.name AS 'person.name',
MIN(group.order_index) AS 'group.order_index',
FROM person
LEFT OUTER JOIN group_has_person ON person.person_id = group_has_person.person_id
LEFT OUTER JOIN group ON group_has_person.group_id = group.workgroup_id
GROUP BY
person.person_id, person.name
ORDER BY
3 ASC, 2 ASC
In other words, if a person belongs to several groups, you can't avoid duplicates unless you pick which order_index to sort by using min, max, avg or sum.
If a person is in several groups, it will have different group.order_indexes associated with it. By which one do you want to sort the person? You could just pick one of them, i.e. the smallest or the largest one, but what sense would that make? Moreover, would it not be disturbing to see a person list sorted by groups, when the groups are not visible in the list? It would be hard for someone who does not know how the list was sorted to figure what kind of sorting logic was applied.

SQL Database SELECT question

Need some help with an homework assignment on SQL
Problem
Find out who (first name and last name) has played the most games in the chess tournament with an ID = 41
Background information
I got a table called Games, which contains information...
game ID
tournament ID
start_time
end_time
white_pieces_player_id
black_pieces_player_id
white_result
black_result
...about all the separate chess games that have taken place in three different tournaments ....
(tournaments having ID's of 41,42 and 47)
...and the first and last names of the players are stored in a table called People....
person ID (same ID which comes up in the table 'Games' as white_pieces_player_id and
black_pieces_player_id)
first_name
last_name
...how to make a SELECT statement in SQL that would give me the answer?
sounds like you need to limit by tournamentID in your where clause, join with the people table on white_pieces_player_id and black_pieces_player_id, and use the max function on the count of white_result = win union black_result = win.
interesting problem.
what do you have so far?
hmm... responding to your comment
SELECT isik.eesnimi
FROM partii JOIN isik ON partii.valge=isik.id
WHERE turniir='41'
group by isik.eesnimi
having count(*)>4
consider using the max() function instead of the having count(*)> number
you can add the last name to the select clause if you also add it to the group by clause
sry, I only speak American. What language is this code in?
I would aggregate a join to that table to a derived table like this:
SELECT a.last_name, a.first_name, CNT(b.gamecount) totalcount
FROM players a
JOIN (select cnt(*) gamecount, a.playerid
FROM games
WHERE a.tournamentid = 47
AND (white_player_id = a.playerid OR black_player_id = a.playerid)
GROUP BY playerid
) b
ON b.playerid = a.playerid
GROUP BY last_name, first_name
ORDER BY totalcount
something like this so that you are getting both counts for their black/white play and then joining and aggregating on that.
Then, if you only want the top one, just select the TOP 1