0

我有 3 张桌子,

  1. 桌子senitems
  2. 桌子inbox
  3. 桌子outbox

如何加入 1 个表,请查看此链接以获取图像说明:

在此处输入图像描述

请帮忙

4

1 回答 1

1

您不需要JOIN为此,您需要的是UNION ALL

SELECT 
  SendingDateTime AS DateTime,
  DestinationNumber AS PhoneNumber,
  SMS,
  'sentitems' AS Folder
FROM sentitems
UNION ALL
SELECT 
  ReceivingDateTime, SenderNumber, SMS,
  'inbox'
FROM inbox
UNION ALL
SELECT 
  InserDateTime, DestinationNumber, SMS,
  'outbox'
FROM outbox;

请注意:最终结果集的列名将从第一个查询中推断出来。


如果要对结果集进行排序,请将该查询放在子查询和ORDER BY外部查询中,如下所示:

SELECT *
FROM
(
    SELECT 
      SendingDateTime AS DateTime,
      DestinationNumber AS PhoneNumber,
      SMS,
      'sentitems' AS Folder
    FROM sentitems
    UNION ALL
    SELECT 
      ReceivingDateTime, SenderNumber, SMS,
      'inbox'
    FROM inbox
    UNION ALL
    SELECT 
      InserDateTime, DestinationNumber, SMS,
      'outbox'
    FROM outbox
) AS sub
ORDER BY DateTime
于 2013-11-10T12:27:59.290 回答