如何在MySQL LEFT JOIN中使用别名

时间:2011-10-15 21:53:40

标签: mysql sql join left-join

我的原始查询是使用WHERE子句而不是JOIN进行连接。我意识到这并没有让那些没有任何明星或类型的电影没有出现,所以我想我必须做一个LEFT JOIN来展示每部电影。这是我原来的SQL:

SELECT *
FROM movies m, stars s, stars_in_movies sm, genres g, genres_in_movies gm
WHERE m.id = sm.movie_id
AND sm.star_id = s.id
AND gm.genre_id = g.id
AND gm.movie_id = m.id
AND m.title LIKE '%the%'
AND s.first_name LIKE '%Ben%'
ORDER BY m.title ASC
LIMIT 5;

我试图对电影进行LEFT JOIN我肯定做错了。

SELECT *
FROM movies m, stars s, stars_in_movies sm, genres g, genres_in_movies gm
LEFT JOIN movies m1 ON m1.id = sm.movie_id
LEFT JOIN movies m2 ON m2.id = gm.movie_id
AND sm.star_id = s.id
AND gm.genre_id = g.id
ORDER BY m.title ASC
LIMIT 5;

我得到ERROR 1054 (42S22): Unknown column 'sm.movie_id' in 'on clause'这么清楚我正在加入错误,我只是看不出它是什么。

5 个答案:

答案 0 :(得分:14)

不要将逗号运算符与JOIN混合 - 它们具有不同的优先级!在manual

中甚至有关于此的警告
  

但是,逗号运算符的优先级小于INNER JOIN,CROSS JOIN,LEFT JOIN等。如果在存在连接条件时将逗号连接与其他连接类型混合,则可能会出现Unknown column 'col_name' in 'on clause'形式的错误。有关处理此问题的信息将在本节后面给出。

请改为尝试:

SELECT *
FROM movies m
LEFT JOIN (
   stars s
   JOIN stars_in_movies sm
       ON sm.star_id = s.id
) ON m.id = sm.movie_id AND s.first_name LIKE '%Ben%'
LEFT JOIN (
    genres g
    JOIN genres_in_movies gm
        ON gm.genre_id = g.id
) ON gm.movie_id = m.id
WHERE m.title LIKE '%the%'
ORDER BY m.title ASC
LIMIT 5;

答案 1 :(得分:3)

您应该将与JOIN相关的条件放在同一个ON子句中。但是,对于上述问题,您应该使用以下查询:

SELECT *
FROM movies m 
LEFT JOIN stars_in_movies sm ON sm.movie_id = m.id
JOIN stars s ON sm.star_id = s.id
LEFT JOIN genres_in_movies gm ON gm.movie_id = m.id
JOIN genres g ON gm.genre_id = g.id
ORDER BY m.title ASC
LIMIT 5;

答案 2 :(得分:1)

也许很难看,但它的工作方式就在这里。要小心这是丑陋的,很多人都在警告这种黑客

SELECT *
FROM movies m, stars_in_movies sm LEFT JOIN movies m1 ON m1.id = sm.movie_id, stars s
ORDER BY m.title ASC
LIMIT 5;

使用联接时,必须使用右表进行连接,该表包含您要比较的列。

答案 3 :(得分:0)

SQL Join(MySQL中的内部联接)

performBlockAndWait

左连接

NSManagedObjectContext *moc = '…; //Our primary context on the main queue

NSManagedObjectContext *private = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[private setParentContext:moc];

[private performBlock:^{
    'Complete your fetch request and update the managed object's property.

    NSError *error = nil;
    if (![private save:&error]) {
        NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
        abort();
    }
    [moc performBlockAndWait:^{
        NSError *error = nil;
        if (![moc save:&error]) {
            NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
            abort();
        }
     }];
}];

正确加入

select emp1.id,emp1.name,emp1.job  from (select id, type as name, description as job from component_type as emp1)emp1
inner join 
emp
on emp1.id=emp.id;

答案 4 :(得分:0)

使用别名连接多个表而不使用连接..

select sum(s.salary_amount) as total_expenses_paid_to_all_department
from salary_mas_tbl s,dept_mas_tbl d
where s.salary_dept=d.dept_id;