从同一个表加入三个查询

时间:2018-03-11 18:49:38

标签: mysql sql join

我必须从同一个表加入3个查询。我试过这段代码:

SELECT t1.`board`
      ,t1.`price`
      ,t2.`price`
      ,t3.`price`
  from boardtype t1
  RIGHT JOIN(SELECT `price`
      from boardtype
      WHERE `acnonac`='ac' AND `roomtype`='single')
  t2 on t1.`board` = t2.`board`
  RIGHT JOIN(
      SELECT 
      `price`
      from boardtype 
      WHERE `acnonac`='ac' AND `roomtype`='double'
  ) t3 on t1.`board` = t3.`board`
WHERE `acnonac`='ac' AND `roomtype`='triple'
ORDER by id

简单地说我正在尝试加入这三个问题:

SELECT `board`,`price` FROM boardtype WHERE `acnonac`='ac' AND `roomtype`='single'
SELECT `board`,`price` FROM boardtype WHERE `acnonac`='ac' AND `roomtype`='double'
SELECT `board`,`price` FROM boardtype WHERE `acnonac`='ac' AND `roomtype`='triple'

我不知道我犯了什么错误。

2 个答案:

答案 0 :(得分:2)

您的子选择中没有board,但您使用它们编写ON子句。

board添加到子选择:

SELECT t1.`board`
      ,t1.`price`
      ,t2.`price`
      ,t3.`price`
  from boardtype t1
  RIGHT JOIN
      (SELECT `price`, `board`
      from boardtype
      WHERE `acnonac`='ac' AND `roomtype`='single') t2 on t1.`board` = t2.`board`
  RIGHT JOIN(
      SELECT `price`, `board`
      from boardtype
      WHERE `acnonac`='ac' AND `roomtype`='double') t3 on t1.`board` = t3.`board`
WHERE `acnonac`='ac' AND `roomtype`='triple'
ORDER by id

答案 1 :(得分:1)

  

也许效率更高

SELECT `boardtype`.`board`
      ,`boardtype`.`price`
  from `boardtype` WHERE `boardtype`.`acnonac`='ac' AND `boardtype`.`roomtype` IN ('single', 'double', 'triple')
  

<强>感谢