duanqu9292 2014-03-26 06:11
浏览 32
已采纳

正确构建我的MySQL JOIN查询

I have 2 tables from which I'm trying to pull data from together in 1 query.

Guilds:
id (int) | guild (varchar)

Challenges:
id (int) | challenger (int) | challengee (int)

The "challenger" and "challengee" fields reference a "id" from the Guilds table. Using one query, I'd like to pull the Guild field for both the "challenger" and "challengee" (based on the "guild id"), but am stuck on the correct syntax to use.

SELECT challenges.`id` AS c_id, challenges.`challengee` AS c_challengee, challenges.`challenger` AS c_challenger, guilds.`guild`
FROM challenges
LEFT JOIN guilds
ON challenges.`challengee` = guilds.`id`

Is it possible building a query that would grab both the "challenger" and "challengee" Guild (field)?

An example of the result I'm trying to achieve:

challenge_id  |  challenger  |  challenger_guild  |  challengee  |  challengee_guild
-------------   -------------  ------------------  --------------  -----------------
2             |      8       |  oBsolete          |      5       |  Plague
  • 写回答

2条回答 默认 最新

  • dongyue7796 2014-03-26 07:36
    关注

    Here you go:

    SELECT t.id, t.challenger, t.g_challenger, t.challengee, g2.guild as g_challengee
    FROM (
      SELECT c1.id, c1.challenger, g1.guild as g_challenger, c1.challengee
      FROM Guilds g1
      JOIN Challenges c1
      ON g1.id = c1.challenger
    ) t 
    JOIN Guilds g2
    ON g2.id = t.challengee
    

    Working Fiddle: http://sqlfiddle.com/#!2/e036d0/18

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数