MySQL新手,请耐心等待。
我正在开发一个收集用户学位的项目。用户可以节省3度,其中类型,主题和学校是可变的。这些关系针对其他查询使用进行了规范化,因此涉及5个表,如下所示(所有列都显示更多列,只包括相关信息)。最后一个,'user_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 |
+------+-----------------------------------------+
机构
+--------+--------------------------------------------+
| id | inst_name |
+--------+--------------------------------------------+
| 000001 | A T Still University of Health Sciences |
| 000002 | Abilene Christian University |
| 000003 | Abraham Baldwin Agricultural College |
+------+----------------------------------------------+
用户
+----------+----------+
| 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 |
+---------+-----------+---------+---------+
如何通过用户x查询'user_degrees'来查找所有度数,但是返回外键的实际值?以用户Test3
为例,我正在寻找像这样的输出(为布局而截断):
+-------------------+-------------------+-------------------+
| 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.. |
+-------------------+-------------------+-------------------+
我猜测混合多个连接,临时表和子查询是答案,但是我很难掌握事物的顺序。非常感谢任何见解,感谢阅读。
答案 0 :(得分:2)
您需要将user_degrees加入度(以及user_degrees引用的其他表)。这个查询将为您提供示例输出:
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
您可能还想阅读本文以了解不同类型的联接:http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
在您学习阶段理解这些内容的唯一方法是实际编写查询,然后修改它们,直到获得所需的输出。