Vinay S Shenoy
Vinay S Shenoy

Reputation: 4028

How can I create a View from multiple rows from multiple tables?

I'm building a database for a chat application and I'm having a spot of trouble building a View to combine the Chats table and the Users table.

The Chats table has fields sender_id, receiver_id which map to the user_id field in the Users table. Now, I want to create a View which will combine the Chats with the Users table, and also provide the sender's and receiver's profile picture(in the fields sender_pic and receiver_pic). These can be fetched from the profile_pic field from the Users table.

What's the SQL syntax for doing this?

Upvotes: 0

Views: 96

Answers (3)

nicopico
nicopico

Reputation: 3636

You need to JOIN the Chats table with the Users table.

As you have 2 joins to the same table (one for the receiver, one for the sender), you'll also need to use table alias to differentiate them:

SELECT Chats.sender_id, Sender.profile_pic as Sender_profile_pic, 
       Chats.receiver_id, Receiver.profile_pic as Receiver_profile_pic, ...
  FROM Chats
  JOIN Users Receiver ON Users.user_id = Chats.receiver_id
  JOIN Users Sender ON Users.user_id = Chats.sender_id

Upvotes: 0

user275683
user275683

Reputation:

Your syntax will be as follows, because you need both sender and receiver you need to join to users table twice.

CREATE VIEW SomeFancyName
AS
    SELECT s.profile_pic AS sender_pic
           ,r.profile_pic AS receiver_pic
        FROM Chats c
        JOIN users s
            ON c.sender_id = s.user_id
        JOIN users r
            ON c.receiver_id = s.user_id

now you can add columns that you need from each

Upvotes: 1

VMai
VMai

Reputation: 10336

You've got to use alias names:

SELECT
    s.profile_pic AS sender_pic,
    r.profile_pic AS receiver_pic
FROM
    Chats
INNER JOIN
    Users AS s      -- s will represent the sender
ON
    Chats.sender_id = s.user_id
INNER JOIN
    Users AS r      -- and r the receiver
ON
    Chats.receiver_id = r.user_id;

Upvotes: 0

Related Questions