如何从多个表中的多行创建视图?

时间:2014-04-05 17:13:46

标签: android sql sqlite view sql-view

我正在为聊天应用程序构建一个数据库,我在构建View以组合Chats表和Users表时遇到了麻烦。

Chats表的字段sender_idreceiver_id映射到user_id表中的Users字段。现在,我想创建一个View,它将ChatsUsers表合并,还会提供发件人和收件人的个人资料图片(在sender_pic字段和{ {1}})。这些可以从receiver_pic表的profile_pic字段中获取。

执行此操作的SQL语法是什么?

3 个答案:

答案 0 :(得分:1)

您的语法如下,因为您需要发送方和接收方都需要两次加入用户表。

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

现在您可以从每个

添加所需的列

答案 1 :(得分:0)

你必须使用别名:

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;

答案 2 :(得分:0)

您需要JOIN Chats表和Users表。

由于你有2个连接到同一个表(一个用于接收者,一个用于发送者),你还需要使用表别名来区分它们:

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