我很难过。我正在尝试编写一个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
答案 0 :(得分: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
。