在mysql中联合命令

时间:2013-05-03 13:05:43

标签: mysql sql sql-order-by union

我需要将两个表的第一列放到一行中,按这两列排序。这是我能够编写的,但它不起作用。

select title from movie 
union 
select reviewer_name from reviewer 
order by title,reviewer_name;

Mysql表示reviewer_name是一个未知列。

enter image description here

4 个答案:

答案 0 :(得分:2)

请你发送电影桌ddl和评论家ddl, 两个表中都存在哪些列?

也许您正在寻找的东西可以通过以下方式解决:

select 
  m.title, 
  r.reviewer_name 
from 
  movie m, 
  reviewer r
where
 m.movieid = r.movieid 
order by m.title, r.reviewer_name;

更新后的问题,你可以这样做:

select
  mo.title,
  rv.reviewer_name,
  ra.stars
from
  movie mo,
  reviewer rv,
  rating ra
where
  mo.movieid = ra.movieid
  and
  ra.reviewerid = rv.reviewerid
order by mo.title, rv.reviewer_name

我也在ms访问中快速完成了这个:

SELECT 
  movie.title, 
  reviewer.reviewer_name, 
  rating.stars
FROM reviewer 
  INNER JOIN (movie INNER JOIN rating ON movie.movieid = rating.movieid) 
  ON reviewer.reviewerid = rating.reviwerid
ORDER BY movie.title, reviewer.reviewer_name

enter image description here

答案 1 :(得分:1)

将两个(或多个)select语句组合在一起时,第一个select语句中的字段名称将用于输出。因此输出只有一个名为“title”的字段。输出中没有“reviewer_name”字段。这就是你收到错误的原因。

select title 
from movie 

union 

select reviewer_name 
from reviewer 

order by title;

答案 2 :(得分:0)

试试:

SELECT * FROM (select title from movie union select reviewer_name from reviewer) as f order by title;

但我认为这里缺少电影和评论者之间的联系......

答案 3 :(得分:0)

帮助排序的另一种可能性

SELECT 0 as a, title
FROM movie
UNION
SELECT 1 as a, reviewer_name as title
FROM reviewer
ORDER BY a, title