使用多个innerjoin时选择所有字段

a14dhokn  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(324)

我有一张这样的table
参与者教练表

id----nutrition_coach----mental_coach----movement_coach
1 ----       2       ----      5     ----      4

教练台

id----name----email----
2 ----NAME---- @@@@ ----

通过 Inner Join 我想得到每个教练的全部数据。
这是我目前的问题

SELECT
    c1 AS nutrition_coach,
    c2 AS movement_coach,
    c3 AS mental_coach
FROM participant_coaches AS pc 
INNER JOIN coaches AS c1 ON pc.nutrition_coach = c1.id 
INNER JOIN coaches AS c2 ON pc.movement_coach = c2.id 
INNER JOIN coaches AS c3 ON pc.mental_coach = c3.id 
WHERE participant = + participantId

这不起作用,它给出了一个错误,它不知道该字段 c1 . 但是,当我只想从我的c1表中选择1个属性时,这就行了。
例如,这是有效的

SELECT c1.id AS nutrition_coach, 
       c2.id AS movement_coach, 
       c3.id AS mental_coach

退货:

mental_coach: 3
movement_coach: 1
nutrition_coach: 2

我是否可以从中选择所有字段 c1 而不是只有1个?
以下是我想要达到的目标
答复:

{
       mental_coach: {
          id: 1
          name: 'MYNAME'
          email '@@@@'
       }
       movement_coach: {
          ...
       }
       nutrition_coach: {
          ...
       }
   }
vmdwslir

vmdwslir1#

id名称电子邮件
你的问题很好,除了 select . mysql没有表示表中整行的“记录”的概念。您需要明确列出列:

SELECT c1.id AS nutrition_coach_id,
       c1.name AS nutrition_coach_name,
       c1.email AS nutrition_coach_email,       
       c2.id AS movement_coach_id,
       c2.name AS movement_coach_name,
       c2.email AS movement_coach_email,
       c3.id AS mental_coach_id,
       c3.name AS mental_coach_name,
       c3.email AS mental_coach_email
x0fgdtte

x0fgdtte2#

select语句只是引用别名,它表示表,但实际上并不表示要使用哪一列。您可能想报告三种不同类型教练的姓名,其中应包括以下内容:

SELECT
    c1.name AS nutrition_coach,
    c1.email AS nutrition_coach_email, -- etc. for other fields
    c2.name AS movement_coach,
    c3.name AS mental_coach
FROM participant_coaches AS pc 
INNER JOIN coaches AS c1
    ON pc.nutrition_coach = c1.id 
INNER JOIN coaches AS c2
    ON pc.movement_coach = c2.id 
INNER JOIN coaches AS c3
    ON pc.mental_coach = c3.id 
WHERE participant = <participantId>

相关问题