【问题标题】:symmetric pair in sqlsql中的对称对
【发布时间】:2020-04-10 20:29:42
【问题描述】:

给定表格 student、maths_marks、science_marks

学生

student_id (Primary Key) | smallint

student_name             | varchar(30)

数学标记

student_id (Primary Key) | smallint

score                      | float (5,2)

科学标记

student_id (Primary Key) | smallint

score                       | float (5,2)

如果该学生在科学中获得的分数与其他学生在数学中获得的分数相等,并且在数学中获得的分数与该学生获得的分数相同,则该学生被称为对称对的一部分其他理科学生。

编写 SQL 查询以打印属于对称对的学生的姓名。按学生姓名的顺序排列输出。

with cte as (
  select m.student_id, m.score as math_score, s.score as science_score 
  from mathematics_marks m inner join science_marks s
  on s.student_id = m.student_id 
)
select s1.student_name
from cte c1 inner join cte c2 
on c2.student_id > c1.student_id and c2.math_score = c1.science_score and c1.math_score = c2.science_score
inner join student s1 on s1.student_id = c1.student_id and s1.student_id = c2.student_id

需要将这对放在两个不同的行中吗?

编辑: 回答这个问题

with cte as (
  select m.student_id, m.score as math_score, s.score as science_score 
  from mathematics_marks m inner join science_marks s
  on s.student_id = m.student_id 
),
T as (select c1.student_id, c1.math_score, c1.science_score, s.student_name as name 
from cte c1 inner join student s 
on c1.student_id = s.student_id )

select t1.name from T t1 inner join T t2 
on t1.math_score = t2.science_score and
t1.science_score = t2.math_score
order by t1.name

【问题讨论】:

  • 您不会有单独的数学和科学表格。在这种情况下,float 是不合适的。应该是 DECIMAL。
  • @Strawberry 我先加入了那两张桌子
  • 那是你当时的第一个错误。那将是一个 UNION。
  • 哦,好的,我也会检查一下,但加入对我有用,谢谢你的帮助
  • 从这个时间开始尝试清楚。

标签: mysql sql join select


【解决方案1】:

如果帖子附带示例数据和预期输出,总是很容易回答。你在找这样的东西吗

Select student.student_id
       ,maths.score maths_socer
       ,sci.score science_score
from 
(
  Select 1 student_id union all
  Select 2 union all
  Select 3
) student
Join 
 (
  Select 1 student_id, 20 score union all
  Select 2, 30 union all
  Select 3, 40
 ) maths
on maths.student_id=student.student_id
Join
(
Select 1 student_id , 30 score union all     
Select 2,20 union all
Select 3,40
) sci on sci.student_id !=student.student_id    
Where sci.score = maths.score

【讨论】:

    【解决方案2】:

    一个设计合理的架构应该有一个学生、学科和分数的表。第一步是模拟该表,如下所示:

    SELECT student_id 
         , 'mathematics' subject
         , score 
      FROM mathematics_marks                    
     UNION  
    SELECT student_id 
         , 'science' 
         , score     
      FROM science_marks                                     
    

    如需进一步帮助,请参阅:Why should I provide an MCRE for what seems to me to be a very simple SQL query?

    【讨论】:

    • 他们(似乎)想要 (s1) 行存在 s2, m, s [m(s1,m) & s(s1,s) & m(s2,s) & s(s2 ,m) & s1s2]。不需要联合,因为所需的学生必须出现在两个表中,而不是任何一个。如果您标记行然后联合,那么您仍然必须使用重新创建原始表的限制的限制进行连接,并且所有所需的学生都出现在连接的(对称)限制的 2 列中的每一列中。所以工会没有任何好处。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多