MySQL JOIN错误:每个派生表必须有自己的别名

时间:2017-05-24 18:00:52

标签: mysql join

我已经看过S.O周围的可能解决方案,但我的查询仍然无法正常工作。

以下是查询:

SELECT `messages`.`from_id`, 
  `messages`.`to_id`, 
  `messages`.`message` 
FROM `messages`
JOIN 
(
  SELECT `users`.`profile_pic` 
  FROM `users` AS `from_pic` 
  WHERE `users`.`id` = `from_id`
)  
  ON `users`.`id` = `messages`.`from_id` 
JOIN 
(
  SELECT `users`.`profile_pic` 
  FROM `users` AS `to_pic` 
  WHERE `users`.`id` = `to_id`
)  
  ON `users`.`id` = `messages`.`to_id` 
WHERE  `messages`.`from_id` = 23 
  AND `messages`.`to_id` = 24 
ORDER BY `date_sent` DESC;

users

id | profile_pic | name

messages

message_id | from_id | to_id | message

2 个答案:

答案 0 :(得分:1)

使用子查询时,需要为它们提供别名:

SELECT 
  `messages`.`from_id`, 
  `messages`.`to_id`, 
  `messages`.`message` 
FROM `messages`
JOIN 
(
  SELECT 
    `from_pic`.`id`, 
    `from_pic`.`profile_pic` 
  FROM `users` AS `from_pic` 
)  u1 --- alias
  ON u1.`id` = `messages`.`from_id` 
JOIN 
(
  SELECT 
    `to_pic`.`id`,
    `to_pic`.`profile_pic` 
  FROM `users` AS `to_pic` 
)  u2 ---- alias
  ON u2.`id` = `messages`.`to_id` 
WHERE  `messages`.`from_id` = 23 
  AND `messages`.`to_id` = 24 
ORDER BY `date_sent` DESC;

这也可以在没有子查询的情况下编写:

SELECT 
  `messages`.`from_id`, 
  `messages`.`to_id`, 
  `messages`.`message` 
FROM `messages`
JOIN `users` AS `from_pic` 
  ON `from_pic` = `messages`.`from_id` 
JOIN `users` AS `to_pic` 
  ON `to_pic`.`id` = `messages`.`to_id` 
WHERE  `messages`.`from_id` = 23 
  AND `messages`.`to_id` = 24 
ORDER BY `date_sent` DESC;

答案 1 :(得分:-1)

您需要将from_pickto_pic别名移出他们不需要的子查询,并在您的加入条件中相应地使用它们,如下所示:

SELECT `messages`.`from_id`, 
  `messages`.`to_id`, 
  `messages`.`message` 
FROM `messages`
JOIN 
(
  SELECT `users`.`profile_pic` 
  FROM `users`
  WHERE `users`.`id` = `from_id`
) AS `from_pic` 
  ON `from_pic`.`id` = `messages`.`from_id` 
JOIN 
(
  SELECT `users`.`profile_pic` 
  FROM `users` 
  WHERE `users`.`id` = `to_id`
)  AS `to_pic` 
  ON `to_pic`.`id` = `messages`.`to_id` 
WHERE  `messages`.`from_id` = 23 
  AND `messages`.`to_id` = 24 
ORDER BY `date_sent` DESC;

更好的是,你甚至不需要子查询:

SELECT `messages`.`from_id`, 
  `messages`.`to_id`, 
  `messages`.`message` 
FROM `messages`
JOIN `users` AS `from_pic` ON `from_pic`.`id` = `messages`.`from_id` 
JOIN `users` AS `to_pic` ON `to_pic`.`id` = `messages`.`from_id` 
WHERE  `messages`.`from_id` = 23 
  AND `messages`.`to_id` = 24 
ORDER BY `date_sent` DESC;