You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何多次关联同一张表获取多CCA字段的对应价格?

解决多次关联同一张表获取多个CCA价格的问题

你遇到的问题很典型——当多次关联同一张表但没给每个关联实例设置不同别名时,数据库无法区分它们,就会抛出“Same aliases”的错误。咱们只需要给每个关联的ccaSubjects表分配独立的别名,分别对应firstCCA、secondCCA、thirdCCA字段,就能顺利获取三个CCA的对应价格了。

正确的SQL查询语句

SELECT
    re.studentIdentifier,
    re.firstCCA,
    re.secondCCA,
    re.thirdCCA,
    c1.ccaPrice AS CCA1price,
    c2.ccaPrice AS CCA2price,
    c3.ccaPrice AS CCA3price
FROM rispEnrollment re
INNER JOIN ccaSubjects c1 ON re.firstCCA = c1.ccaSubject
INNER JOIN ccaSubjects c2 ON re.secondCCA = c2.ccaSubject
INNER JOIN ccaSubjects c3 ON re.thirdCCA = c3.ccaSubject;

代码解释

  • 给rispEnrollment设置别名re,让代码更简洁易读;
  • 第一次关联ccaSubjects时用别名c1,匹配firstCCA字段,取出对应的价格作为CCA1price;
  • 第二次关联用别名c2,匹配secondCCA字段,取出CCA2price;
  • 第三次关联用别名c3,匹配thirdCCA字段,取出CCA3price;
  • 每个关联的ccaSubjects表都有独立的别名,数据库就能准确区分不同的关联逻辑,不会再报错。

执行这条SQL后,就能得到你期望的输出结果:

+--------------------+-----------+-----------+----------+-----------+-----------+-----------+
| 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       |
+--------------------+-----------+-----------+----------+-----------+-----------+-----------+

内容的提问来源于stack exchange,提问作者Muhamad Hafizuddin Afiq Bin An

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:37:02