根据发件人从用户表中选择数据,另一个表中选择收件人ID

时间:2019-07-07 01:48:56

标签: mysql

我无法正确设置此SQL查询的格式。我想做的是从一个活动表中选择数据,并从存储在该活动表中的两个用户的ID中选择数据。我当前的声明如下:

SELECT activity.id, activity.sender, activity.recipient, activity.amount, activity.description, activity.create_date, users.first_name, users.last_name, users.username, users.profile_photo FROM `activity` INNER JOIN `users` ON users.id = activity.sender ORDER BY activity.create_date DESC

现在,这将获取activity.sender用户的数据,但我希望将查询扩展为包括activity.recipient用户。我玩过“ GROUP BY activity.recipient,activity.sender”和GROUP_CONCAT(users.first_name,users.last_name等)等不同的东西,但是没有成功。

更新的查询:

SELECT activity.id, activity.sender, activity.recipient, activity.amount, activity.description, activity.create_date, users.first_name, users.last_name, users.username, users.profile_photo, recipient.first_name, recipient.last_name, recipient.username FROM `activity` INNER JOIN `users` ON users.id = activity.sender INNER JOIN 'users' AS recipient ON activity.recipient = recipient.id ORDER BY activity.create_date DESC

仍然出现SQL语法错误:'您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以获取正确的语法,以在\'\'users \'AS收件人ON活动附近使用。recipient= receiver.id ORDER BY activity.crea \'在第1行'

1 个答案:

答案 0 :(得分:0)

不太清楚您要问什么,但我会给您一个机会。

我认为您需要在查询中包括两次User表,一次是查找发件人,第二次是查找收件人。如果是这样,查询将看起来像这样

SELECT activity.*, users.*, receiver_user.first_name, receiver_user.last_name
FROM `activity`  INNER JOIN `users` 
        ON users.id = activity.sender 
      inner join 'users' as 'receiver_user'
        ON activity.recipient = users.id
ORDER BY activity.create_date DESC

请注意,我为您的users表使用了 alias 来“内部连接'users'为'receiver_user'。还请注意,我知道很多SQL,但对mySql却了解不多。引号可能是错误的。