将3个表中的3列加入到不同的行记录中

时间:2013-11-10 12:23:40

标签: mysql

我有3张桌子,

  1. senitems
  2. inbox
  3. outbox
  4. 如何加入1个表格,请查看此链接以获取图片说明:

    enter image description here

    请帮助

1 个答案:

答案 0 :(得分: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