如何在此联合结果中添加列?

时间:2010-06-11 16:56:33

标签: mysql union

我有这个查询(我为了简洁而删除了一些键):

SELECT id as in_id, out_id, recipient, sender, read_flag 
  FROM received WHERE recipient=1
UNION ALL 
SELECT in_id, id AS out_id, recipient, sender, read_flag  
  FROM sent WHERE sender=1 

它结合了两个表的结果,显示给定用户发送和接收的消息。我想要做的是在结果中添加一个列/标志以区分该行所属的表,因此当我显示它时,我可以显示已发送或已接收消息的相关图标。我该如何添加?

3 个答案:

答案 0 :(得分:20)

只需为每个查询添加一个常量列。只要它在两个部分都是相同的,那么类型是什么并不重要。所以你可以使用0和1或两个字符串,例如:

SELECT id as in_id, out_id, recipient, sender, read_flag , 'received' as source
  FROM received WHERE recipient=1
UNION ALL 
SELECT in_id, id AS out_id, recipient, sender, read_flag , 'sent' as source 
  FROM sent WHERE sender=1 

答案 1 :(得分:3)

只需在每个选择中添加一个带有硬编码值的列:

SELECT id as in_id, out_id, recipient, sender, read_flag, 'received' as source_table 
  FROM received WHERE recipient=1
UNION ALL 
SELECT in_id, id AS out_id, recipient, sender, read_flag, 'sent' as source_table 
  FROM sent WHERE sender=1 

答案 2 :(得分:2)

这样做:

SELECT 'r' as type, id as in_id, out_id, recipient, sender, read_flag 
  FROM received WHERE recipient=1
UNION ALL 
SELECT 's' as type, in_id, id AS out_id, recipient, sender, read_flag  
  FROM sent WHERE sender=1