在一个表mysql上加入多个查询

时间:2017-02-06 11:42:20

标签: mysql

我如何在mysql中实现这一目标?

结果表

+ ----------------- + ----------------------- + ---- - +
  | st-id |术语|比分|
  + ----------------- + ----------------------- + ------ +
  | 20001 | 1 | 5 |
  | 20002 | 1 | 6 |
  | 20001 | 2 | 6 |
  | 20002 | 2 | 4 |
  | 20003 | 1 | 7 |
  | 20003 | 2 | 9 |
  
+ ----------------- + ----------------------- + ------ + -

结果查询应该是这样的

+ -------------------------------- +
  | st-id |得分 - >术语1 |得分 - >术语2
  + ------------------------------- +
  | 20001 | 5 | 6 |
  | 20002 | 6 | 4 |
| 20003 | 7 | 9 |

+ ------------------------------- +

尝试

(select st-id from result-table where term=1) union (select st-id from result-table where term=2) 

但它会附加结果。

1 个答案:

答案 0 :(得分:0)

你应该使用一个联接(如果行总是匹配,那么总是匹配内部的<)>

  select a.st-id, a.score as `score->term 1`,  b.score as `score->term 2` 
  from `result-table` as a  
  left join `result-table` as a   on a.`st-id` = b.`st-id`
  where a.term=1
  and b.term=2

  select a.`st-id`, a.score as `score->term 1`,  b.score as `score->term 2` 
  from `result-table` as a  
  inner join `result-table a`s a   on a.`st-id` = b.`st-id`
  where a.term=1
  and b.term=2

并且你不应该使用name作为st-id( - 是mysql中的操作符)..如果你真的需要使用backtics