如何将一个表与另一个表的单独条件联接起来

时间:2019-05-23 11:16:38

标签: mysql join

我的数据库中有以下表格:

campuses
+----+--------+----------+--------+------+
| Id | Campus | Location | County | Year |
+----+--------+----------+--------+------+
discEnr
+----------+------------+------+----+----+
| CampusId | Discipline | Year | Ug | Gr |
+----------+------------+------+----+----+
disciplines
+----+------+
| Id | Name |
+----+------+

问题: 报告2004年“农业”和“生物科学”领域任何一所同时提供这两个学科研究生课程的大学的研究生入学情况。在每所大学中报告一行(两个研究生的入学人数在单独的列中),然后按“农业”研究生的人数对大学进行降序排列。

我了解如何报告“农业”或“生物科学” 如下,但不是同时在一个输出表中将两者结合在一起

THIS WORKS FOR JUST 'Agriculture'

SELECT c.Campus, DE1.Gr Agriculture
FROM discEnr DE1
JOIN disciplines d1
  ON d1.Id = DE1.Discipline
 AND d1.Name = 'Agriculture'  
JOIN campuses c
  ON c.Id = DE1.CampusId
 AND DE1.year = 2004
ORDER BY DE1.Gr DESC;

我最近的尝试给了我一个空集,这是不正确的,但是我不太确定从这里去哪里:

SELECT c.Campus, DE1.Gr Agriculture, DE2.Gr Biology
FROM discEnr DE1
JOIN disciplines d1
  ON d1.Id = DE1.Discipline
 AND d1.Name = 'Agriculture'  
JOIN discEnr DE2
  ON DE1.CampusId = DE2.CampusId
JOIN disciplines d2
  ON d2.Id = DE2.Discipline
 AND d1.Name = 'Biological Sciences'
JOIN campuses c
  ON c.Id = DE1.CampusId
 AND DE1.year = 2004
ORDER BY DE1.Gr DESC;

最终,我的输出应采用以下格式:

+-----------------+------------------------+--------------------+
| campuses.Campus | discEnr.Gr Agriculture | discEnr.Gr Biology |
+-----------------+------------------------+--------------------+

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

u可以使用OR运算符。


SELECT c.Campus, DE1.Gr 
FROM discEnr DE1
JOIN disciplines d1 ON d1.Id = DE1.Discipline 
JOIN disciplines d2 ON d2.Id = DE1.Discipline 
JOIN campuses c ON c.Id = DE1.CampusId AND DE1.year = 2004
where d1.Name = 'Agriculture' or d2.Name = 'Biological Sciences'
ORDER BY DE1.Gr DESC;

请提供您的样本数据集以帮助我们完善答案

答案 1 :(得分:0)

我实际上找到了一个可行的解决方案。我不确定会是哪种更优雅的方式,但这确实可行。如果您知道更简短或更易读的方式,请随时发布!

SELECT c.Campus, DE1.Gr Agriculture, DE2.Gr Biology
FROM discEnr DE1
JOIN disciplines d1
  ON d1.Id = DE1.Discipline
 AND d1.Name = 'Agriculture'
 AND DE1.Gr > 0

JOIN discEnr DE2
  ON DE1.CampusId = DE2.CampusId
JOIN disciplines d2
  ON d2.Id = DE2.Discipline
 AND d2.Name = 'Biological Sciences'
 AND DE2.Gr > 0

JOIN campuses c
  ON c.Id = DE1.CampusId
 AND DE1.year = 2004
ORDER BY DE1.Gr DESC;

这实际上与我的原始解决方案非常接近,但是在我的原始帖子中,我放了 d1 。Name='Biological Sciences'而不是 d2 .Name ='Biological Sciences'