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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题