Join same field multiple times in table - mysql

I have this 2 tables and I am trying to join both of them multiple times but failed. Below are the tables.
Table ccaSubjects:
+------------+----------+
| ccaSubject | ccaPrice |
+------------+----------+
| Chess | 100 |
| Badminton | 300 |
| Dancing | 200 |
| Singing | 200 |
| Football | 250 |
| Fitness | 600 |
| Robotics | 1000 |
+------------+----------+
Table rispEnrollment
+--------------------+-----------+-----------+----------+
| studentIdentifier | firstCCA | secondCCA | thirdCCA |
+--------------------+-----------+-----------+----------+
| elly#example.com | Robotics | Singing | Dancing |
| mike#example.com | Chess | Singing | Robotics |
| tom#example.com | Badminton | Dancing | Chess |
| peter#example.com | Football | Fitness | Robotics |
| andrew#example.com | Robotics | Singing | Chess |
+--------------------+-----------+-----------+----------+
I would like my output to be like:
+--------------------+-----------+-----------+----------+-----------+-----------+-----------+
| studentIdentifier | firstCCA | secondCCA | thirdCCA | CCA1price | CCA2price | CCA3price |
+--------------------+-----------+-----------+----------+-----------+-----------+-----------+
| elly#example.com | Robotics | Singing | Dancing | 1000 | 200 | 200 |
| mike#example.com | Chess | Singing | Robotics | 100 | 200 | 1000 |
| tom#example.com | Badminton | Dancing | Chess | 300 | 200 | 100 |
| peter#example.com | Football | Fitness | Robotics | 250 | 600 | 1000 |
| andrew#example.com | Robotics | Singing | Chess | 1000 | 200 | 100 |
+--------------------+-----------+-----------+----------+-----------+-----------+-----------+
From my code, I am only able to use an inner join one time and get the CCA1price, and I cannot get cca2price and cca3price anymore because the error keeps saying Same aliases.

You may join the rispEnrollment table to the ccaSubjects table as many times as you need. In this case, you may join three times to bring in the price columns for each of the three subject columns.
SELECT
t1.studentIdentifier,
t1.firstCCA,
t1.secondCCA,
t1.thirdCCA,
t2.ccaPrice AS CCA1price,
t3.ccaPrice AS CCA2price,
t4.ccaPrice AS CCA3price
FROM rispEnrollment t1
LEFT JOIN ccaSubjects t2
ON t1.firstCCA = t2.ccaSubject
LEFT JOIN ccaSubjects t3
ON t1.secondCCA = t3.ccaSubject
LEFT JOIN ccaSubjects t4
ON t1.thirdCCA = t4.ccaSubject;
Note that I use left joins here just in case the rispEnrollment table might have a subject which does not match to anything in the ccaSubjects table.

Related

How to SELECT data from 5 different tables in MySQL

I am trying to select data from multiple tables. The main table is Notices.
Table: Notices
+-------+-------------+----------------+
| id | notice_code | company_number |
+-------+-------------+----------------+
| 96008 | 2410 | 09844265 |
| 96014 | 2450 | 02640968 |
| 96032 | 2443 | 03666759 |
+-------+-------------+----------------+
I have to select related information for the rows for Table Notice from different tables. Below are the other 4 tables and their relation with table Notices
Table Companies has a direct relation with Table Notices
Table: Companies
Companies.Company_number = Notices. Company_ Number
+----------------+--------------+-------+
| company_number | company_name | sic1 |
+----------------+--------------+-------+
| 02640968 | XYZ Logistic | 28220 |
| 03666759 | OPQ Logistic | 41100 |
| 09844265 | ABC Logistic | 49410 |
+----------------+--------------+-------+
Table Sic_codes doesn’t have a direct relation with Table Notices. But it has with Table Companies.
Table: Sic_Codes.
Companies.Sic1 = Sic_code.Code
+-------+----------------+
| code | sector |
+-------+----------------+
| 28220 | Manufacture |
| 41100 | Construction |
| 49410 | Transportation |
+-------+----------------+
Table Insovency_Practionar does not have a direct relation with Table Notices. There is another Table Notice_insolvency_practitionar_ID to create a relation between these two tables Table Insovency_Practionar and Table Notices
Table: Notice_insolvency_practitionar_ID .
Notice_insolvency_practitionar_ID. Notice_ID = Notices. ID
+-----------+----------------------------+
| notice_id | insolvency_practitioner_id |
+-----------+----------------------------+
| 96008 | 1048 |
| 96008 | 725 |
| 96032 | 548 |
+-----------+----------------------------+
Table: Insovency_Practionar .
Insovency_Practionar.ID = Notice_insolvency_practitionar_ID. Insolvency_Practiotionar_ID
+------+---------+
| id | name |
+------+---------+
| 548 | Charlie |
| 725 | Bill |
| 1048 | Andrew |
+------+---------+
My expected output is the following: where company name will be coming from table company; sic1 and sector will come from table sic_code and practitioner will come from table Insovency_Practionar
+----------------+--------------+-------+----------------+--------------+
| company_number | company_name | sic1 | sector | practitioner |
+----------------+--------------+-------+----------------+--------------+
| 9844265 | ABC Logistic | 49410 | Transportation | Andrew |
| 2640968 | XYZ Logistic | 28220 | Manufacture | Bill |
| 3666759 | OPQ Logistic | 41100 | Construction | Charlie |
+----------------+--------------+-------+----------------+--------------+
I have used LEFT Join in my QUERY.
Here is my query
SELECT n.company_number
, c.company_name
, c.sic1
, s.sector
,i.name practitioner
FROM notices n
LEFT JOIN companies c
ON c.company_number = n.company_number
LEFT JOIN sic_codes s
ON s.code = c.sic1
LEFT JOIN notice_insolvency_practitioners ni
ON ni.notice_id = n.id
LEFT JOIN insolvency_practitioners i
ON i.id = ni.insolvency_practitioner_id
where n.notice_code =2410
Here is my SQL Fiddle. http://sqlfiddle.com/#!9/4887e2/2
I wanted to know if my query was right. Or is there any other better way to write the query. As initially, the query gave me wrong result when I was testing.
Update: I have figured out there was a duplicate entry. And that was the reason for not getting the expected output. I have now corrected that. But still want to know if my query is right or is there a better way to write the query
I have figured out what the problem was. Thanks to #Viney
<pre>
+-----------+----------------------------+
| notice_id | insolvency_practitioner_id |
+-----------+----------------------------+
| 96008 | 1048 |
| 96008 | 725 |
| 96032 | 548 |
+-----------+----------------------------+
</pre>
duplicate entry for notice id 96008. It should be like
<pre>
+-----------+----------------------------+
| notice_id | insolvency_practitioner_id |
+-----------+----------------------------+
| 96008 | 1048 |
| 96014 | 725 |
| 96032 | 548 |
+-----------+----------------------------+
</pre>
I have also edited My question and have reduced the extra columns to make it readable for users

What is the top movie genre using the average rank per movie genre as the metric?

Currently, I am teaching my self SQL and i came across a very interesting question which says:
Based ratings with 10,000 or more votes, what is the top movie genre using the
average rank per movie genre as the metric?
(Note: where a higher value for rank is considered a better movie)
So here are the tables: rating
+---------+------+--------+--------------+
| movieid | rank | votes | distribution |
+---------+------+--------+--------------+
| 1672052 | 7.8 | 8111 | 0000001222 |
| 1672111 | 5.3 | 32183 | 0001221000 |
| 1672580 | 4.4 | 1894 | 0011110000 |
| 1672716 | 7.0 | 1255 | 0000001212 |
| 1673647 | 6.5 | 128 | 0000111211 |
| 1673658 | 3.9 | 20 | 22101.10.1 |
| 1673848 | 7.0 | 137748 | 0000012211 |
| 1674388 | 5.5 | 47380 | 0001221000 |
Table: movie_directores
+---------+------------+-------------+
| movieid | directorid | genre |
+---------+------------+-------------+
| 1672052 | 22397 | Drama |
| 1672111 | 54934 | Action |
| 1672580 | 297253 | Comedy |
| 1672716 | 188926 | Drama |
| 1672946 | 188940 | Action |
| 1673647 | 302682 | Drama |
| 1673658 | 155385 | Comedy |
| 1673848 | 133605 | Comedy |
| 1674388 | 115990 | Adventure |
| 1674737 | 164962 | Drama |
| 1677011 | 116812 | Comedy |
| 1677258 | 99002 | Comedy |
| 1677346 | 22912 | Biography |
what I want is: Based on ratings with 10,000 or more votes, I want to know what is the top movie genre using the average rank per movie genre as the metric
what I did so far is this:
SELECT movieid
FROM rating m
JOIN (
SELECT movieid, COUNT(movieid)
FROM rating)
ON m.movieid = r.movieid
count(*)>=10000
not sure if the logic is correct . any help?
Consider:
select md.genre, avg(r.rank) avg_rank
from movies_directores md
inner join rating r on r.movieid = md.movieid
where r.votes > 10000
group by md.genre
order by avg(r.rank) desc
limit 1

MySql how to get a name based on a primary in the same row?

I want to show some data from the database. The id of the boss is in the same row as an employee. I want to display the name of the boss. eId is the id of the employee and bossId is the id of his boss. recepId is the id of the receptionist of that department.
I want to show the department name, description, id of the receptionist, name of the receptionist, id of the boss and his name.
I can display everything except the name of the boss. How do manage that inside my query?
Employee table:
| eId | name |city |bossId | depNr |
|:-------------|------------:|:------------:|--------------------
| 345 | Frits | Canvas | 240 | 60|
| 240 | Steven | Canvas | 200 | 90|
| 265 | John | Kentucky | 40 | 60|
| 40 | Kreuger | Kentucky | | 90|
Department table:
| depCode | depName |locId |recepId|
|:-------------|------------: |:-----------|----------
| 60 | Finance | CAN | 345 |
| 90 | Research | CAN | 265 |
Location table:
| code | description |country |
|:-------------|------------: |:-----------|
| CAN | Finance | USA |
| CAN | Research | USA |
| KEN | Economics | USA |
What I want:
| depName | description |recepId |name | bossID| bossName|
|:-------------|------------:|:------------:|----------------------------
| 345 | COD12 | Canvas | Frits | 240 | Steven
| 140 | COD40 | Canvas | John | 800 | Kreuger
My query:
SELECT department.depName, Location.description, department.recepId, employee.name, employee.bossId
FROM department
INNER JOIN Location
ON Location.code = department.locId
Left JOIN employee
ON department.recepId = employee.eId
This shows:
| depName | description |recepId |name | bossID|
|:-------------|------------:|:------------:|-------------------
| 345 | COD12 | Canvas | Frits | 240 |
| 140 | COD40 | Canvas | John | 800 |
Join with employee again to get the boss's name.
SELECT department.depName, Location.description, department.recepId,
employee.name, employee.bossId, boss.name AS bossName
FROM department
INNER JOIN Location
ON Location.code = department.locId
Left JOIN employee
ON department.recepId = employee.eId
LEFT JOIN employee AS boss
ON employee.bossId = boss.eId

Compare different rows and bring out result

I have a table which requires me to pair certain rows together using a unique value that both the rows share.
For instance in the below table;
+--------+----------+-----------+-----------+----------------+-------------+
| id | type | member | code | description | matching |
+--------+----------+-----------+-----------+----------------+-------------+
| 1000 |transfer | 552123 | SC120314 | From Gold | |
| 1001 |transfer | 552123 | SC120314 | To Platinum | |
| 1002 |transfer | 833612 | SC120314 | From silver | |
| 1003 |transfer | 833612 | SC120314 | To basic | |
| 1004 |transfer | 457114 | SC150314 | From Platinum | |
| 1005 |transfer | 457114 | SC150314 | To silver | |
| 1006 |transfer | 933276 | SC180314 | From Gold | |
| 1007 |transfer | 933276 | SC180314 | From To basic | |
+--------+----------+-----------+-----------+----------------+-------------+
basically What i need the query / routine to do is find the rows where the value in the 'member' column for each row match. Then see if the values in the 'code' column for the same found rows also match.
If both columns for both rows match, then assign a value to the 'matching' column for both rows. This value should be the same for both rows and unique to only them.
The unique code can be absolutely anything, so long as it's exclusive to matching rows. Is there any query / routine capable of carrying this out?
I'm not sure I understand the question correctly, but if you like to pick out and update rows where the code and member columns matches and set matching to some unique value for each of the related rows, I believe this would work:
UPDATE <table> A
INNER JOIN (SELECT * FROM <table>) B ON
B.member = A.member && B.code = A.code && A.id <> B.id
SET A.matching = (A.id + B.id);
The matching value will be set to the sum of the id columns for both rows. Notice that updating the matching field this way will not work if there are more than two rows that can match.
Running the above query against your example table would yield:
+------+----------+--------+----------+---------------+----------+
| id | type | member | code | description | matching |
+------+----------+--------+----------+---------------+----------+
| 1000 | transfer | 552123 | SC120314 | From Gold | 2001 |
| 1001 | transfer | 552123 | SC120314 | To Platinum | 2001 |
| 1002 | transfer | 833612 | SC120314 | From Silver | 2005 |
| 1003 | transfer | 833612 | SC120314 | To basic | 2005 |
| 1004 | transfer | 457114 | SC150314 | From Platinum | 2009 |
| 1005 | transfer | 457114 | SC150314 | To silver | 2009 |
| 1006 | transfer | 933276 | SC180314 | From Gold | 2013 |
| 1007 | transfer | 933276 | SC180314 | From To basic | 2013 |
+------+----------+--------+----------+---------------+----------+
I can give you a simple query what can do what you need.
tst is the name of the table.
SELECT *, COUNT( t2.id ) as matching FROM tst t LEFT JOIN tst t2 ON t2.member = t.member GROUP BY t.id

How to Query a Table with Multiple Foreign Keys and Return Actual Values

New to MySQL, so please bear with me.
I'm working on a project that collects user's degrees. Users can save 3 degrees where the type, subject matter, and school are variable. These relations are normalized for other query uses so 5 tables are involved and are shown below (all have more columns then shown, just included the relevant info). The last one, 'user_degrees' is where the keys come together.
degrees
+----+-------------------+
| id | degree_type |
+----+-------------------+
| 01 | Bachelor's Degree |
| 02 | Master's Degree |
| 03 | Ph.D. |
| 04 | J.D. |
+----+-------------------+
acad_category
+------+-----------------------------------------+
| id | acad_cat_name |
+------+-----------------------------------------+
| 0015 | Accounting |
| 0026 | Business Law |
| 0027 | Finance |
| 0028 | Hotel & Restaurant Management |
| 0029 | Human Resources |
| 0030 | Information Systems and Technology |
+------+-----------------------------------------+
institutions
+--------+--------------------------------------------+
| id | inst_name |
+--------+--------------------------------------------+
| 000001 | A T Still University of Health Sciences |
| 000002 | Abilene Christian University |
| 000003 | Abraham Baldwin Agricultural College |
+------+----------------------------------------------+
users
+----------+----------+
| id | username |
+----------+----------+
| 00000013 | Test1 |
| 00000018 | Test2 |
| 00000023 | Test3 |
+----------+----------+
user_degrees
+---------+-----------+---------+---------+
| user_id | degree_id | acad_id | inst_id |
+---------+-----------+---------+---------+
| 18 | 1 | 4 | 1 |
| 23 | 1 | 15 | 1 |
| 23 | 2 | 15 | 1 |
| 23 | 3 | 15 | 1 |
+---------+-----------+---------+---------+
How can I query 'user_degrees' to find all degrees by user x, but return the actual values of the foreign keys? Taking user Test3 as an example, I'm looking for output like so (truncated for layout's sake):
+-------------------+-------------------+-------------------+
| degree_type | acad_cat_name | inst_name |
+-------------------+-------------------+-------------------+
| Bachelor's Degree | Accounting | A T Still Uni.. |
| Master's Degree | Accounting | A T Still Uni.. |
| Ph.D. | Accounting | A T Still Uni.. |
+-------------------+-------------------+-------------------+
I'm guessing a mix of multiple joins, temp tables and subqueries are the answer but am having trouble grasping the order of things. Any insight is much appreciated, thanks for reading.
You need to join user_degrees to degrees (and the other tables referenced by user_degrees). This is the query that will give you your example output:
SELECT
ud.user_id, d.degree_type, ac.acad_cat_name, i.inst_name
FROM
user_degrees ud
INNER JOIN degrees d ON d.id = ud.degree_id
INNER JOIN acad_category ac ON ac.id = ud.acad_id
INNER JOIN institutions i ON i.id = ud.inst_id
WHERE
ud.user_id = 18
You may also want to read this article to understand different kinds of joins: http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
The only way to understand these things at your stage of learning is to actually write the queries and then modify them until you get your desired output.