首页 文章

带有两个引用ONE的列的SQLite查询

提问于
浏览
1

我很难过 . 我正在尝试编写一个SQLite查询,其中有两个表 . 一个表有两列,它们都指向第二个表中的同一列 . 例如,

Table1
ID     Text     Sender     Recipient    
1     Hi There  1          2 
2     What?     2          1
3     Weirdo!   3          1

Table2
ID    Name     Screenname
1     Me       Me
2     Sally    Sal_gal
3     Bob      Bob

我试图编写查询,我会得到以下结果,因为Table1的Sender和Recipient都指向Table2中的ID .

Results
ID       Text       Sender       Recipient
1       Hi There    Me           Sally
2       What?       Sally        Me
3       Weirdo      Bob          Me

1 回答

  • 0

    使用 JOIN 两次:

    SELECT t1.ID, t1.Text, t2.Name AS Sender, t3.Name AS Recipient
    FROM Table1 t1
    JOIN Table2 t2
      ON t1.Sender = t2.ID
    JOIN Table2 t3
      ON t1.Recipient = t3.ID;
    

    LiveDemo

    输出:

    ╔════╦══════════╦════════╦═══════════╗
    ║ ID ║   Text   ║ Sender ║ Recipient ║
    ╠════╬══════════╬════════╬═══════════╣
    ║  1 ║ Hi There ║ Me     ║ Sally     ║
    ║  2 ║ What?    ║ Sally  ║ Me        ║
    ║  3 ║ Weirdo!  ║ Bob    ║ Me        ║
    ╚════╩══════════╩════════╩═══════════╝
    

    我已经说过你已经在两个表之间定义了外语 . 否则您可能需要使用 LEFT JOIN .

相关问题