在MYSQL中使用JOIN语句显示来自两个不同表的数据

时间:2017-04-20 20:15:29

标签: mysql

我试图让它显示,但每次我尝试时,都会说“空集”而不是向我展示我需要的东西。 Here is an image of the database schema

以下是我的要求:

构造SQL语句以查找message.sender_id = 1发送的所有消息。注意:必须使用WHERE子句来设置此查询的条件。显示以下列: - 发件人的名字 - 发件人的姓氏 - 接收者的名字 - 收件人的姓氏 - 消息ID - 信息 - 消息时间戳

这是我提出的MYSQL代码,但就像我说的那样,它只返回并且空集。

SELECT
 person.first_name AS "Sender's first name",
 person.last_name AS "Sender's last name",
 person.first_name AS "Receiver's first name",
 person.last_name AS "Receiver's last name",
 message.message_id AS "Message ID",
 message.message AS "Message",
 message.send_datetime AS "Message Timestamp"
FROM message
 JOIN person ON message.sender_id = person.person_id AND message.receiver_id = person.person_id
WHERE message.sender_id = 1;

我无法弄清楚如何根据消息表中的发件人和收件人ID获取人员表的名字和姓氏。

任何帮助都会很棒!谢谢!

3 个答案:

答案 0 :(得分:1)

您需要加入person两次。一个连接获取发送者信息,一个接收者。当您使用同一个表两次时,您需要在查询中对其进行别名。有点像...

SELECT
  msg_sender.first_name AS "Sender's first name",
  msg_sender.last_name AS "Sender's last name",
  msg_receiver.first_name AS "Receiver's first name",
  msg_receiver.last_name AS "Receiver's last name",
  message.message_id AS "Message ID",
  message.message AS "Message",
  message.send_datetime AS "Message Timestamp"
FROM message
JOIN person AS msg_sender ON message.sender_id = msg_sender.person_id 
JOIN person AS msg_receiver ON message.receiver_id = msg_receiver.person_id 
WHERE message.sender_id = 1;

答案 1 :(得分:0)

您需要在Person上join两次,以下情况应该有效:

SELECT s.first_name, s.last_name, r.first_name, r.last_name, m.message_id, m.send_datetime, m.message
FROM person s JOIN message m ON s.person_id = m.sender_id
JOIN person r ON m.receiver_id = r.person_id
WHERE s.person_id = 1;

答案 2 :(得分:0)

你写的那个看起来像你的person_id形式的人表必须是" 1" - 你的消息表中的sender_id和receiver_id也必须等于" 1" 这是一个非常苗条的集合,或者只是完全无效。

Select 
 t2.first_name AS "Sender's first name",
 t2.last_name AS "Sender's last name",
 t3.first_name AS "Receiver's first name",
 t3.last_name AS "Receiver's last name",
 t1.message_id AS "Message ID",
 t1.message AS "Message",
 t1.send_datetime AS "Message Timestamp"
FROM
  message t1
JOIN (SELECT first_name, last_name, person_id FROM person) t2 
  ON message.sender_id = t2.person_id
JOIN (SELECT first_name, last_name, person_id FROM person) t3
  ON message.receiver_id = t3.person_id
WHERE
 message.sender_id = 1

我没有这样做,但它应该让你知道要写什么。