加入4个桌子

时间:2013-03-12 02:43:23

标签: mysql

以下是架构和示例查询的小提琴:http://sqlfiddle.com/#!2/573ec4/9

我希望使用I.section和L.level返回C.price,这是通过其他联接获得的。当使用内部联接和成本时,我没有结果:http://sqlfiddle.com/#!2/573ec4/2

由于费用是一个将部分和级别映射到价格的表格,我希望能够计算查询中所有展示的价格

4 个答案:

答案 0 :(得分:1)

当您加入Cost表时,您没有包含正确的连接条件:

INNER JOIN `cost` `C` 
  ON `I`.`Section` = c.section  -- = c.section is missing
  AND `L`.`level` = c.level;  -- = c.level is missing

所以你的完整查询将是:

SELECT  `F`.`date`,
  `F`.`time`,
  `F`.`tname`,
  `I`.`section`,
  `L`.`level`,
  c.price
FROM `booking_for_schedule` `F`
INNER JOIN `booking_in_seats` `I` 
  on `F`.`tname`=`I`.`tname` 
  AND `F`.`booking_num` = `I`.`booking_num`
INNER JOIN `level` `L` 
  on `F`.`date`=`L`.`date` 
  AND `F`.`time`=`L`.`time` 
  AND `F`.`tname`=`L`.`tname`
INNER JOIN `cost` `C` 
  ON `I`.`Section` = c.section
  AND `L`.`level` = c.level;

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

看起来你遗漏了INNER JOIN cost C上的一些条款(当你加入Cost表时)。

它应该是这样的:

INNER JOIN `cost` `C` ON `I`.`Section`=`C`.`Section` AND `L`.`level`=`C`.`level`

而不是:

INNER JOIN `cost` `C` ON `I`.`Section` AND `L`.`level`

答案 2 :(得分:0)

您错过了加入专栏。你没有结果的原因是因为I.Section AND L.level总是会返回false。

SELECT  F.date,
        F.time,
        F.tname,
        I.section,
        L.level,
        c.*
FROM    booking_for_schedule F
        INNER JOIN booking_in_seats I 
            ON  F.tname = I.tname AND 
                F.booking_num = I.booking_num
        INNER JOIN level L 
            ON  F.date = L.date AND 
                F.time = L.time AND 
                F.tname = L.tname
        INNER JOIN cost C 
            ON  I.Section = C.Section AND  -- <<== HERE
                L.level = C.level          -- <<== HERE

答案 3 :(得分:0)

你的最后一行是问题所在:

INNER JOIN `cost` `C` ON `I`.`Section` AND `L`.`level`

应该是这样的:

INNER JOIN `cost` `C` ON `I`.`Section` = `C`.`Section` AND `L`.`level` = `C`.`Level`