如何使用Delphi SQL将2个表中的2个字段组合成一个字段

时间:2015-08-19 19:02:27

标签: sql delphi

我试图将2个表中的2个字段组合成一个字段,而不是使用 Delphi SQL 将一个记录合并。

这就是我的表格:

表1:

   ItemID
   ------
   E001
   E002
   E004
   I001

表2:

   ItemID
   ------
   E002
   E003
   I001
   I002

ItemID服务器作为两个表之间的关键字。我正在尝试编写一个返回以下内容的查询:

   ItemID
   E001 
   E002
   E003 
   E004 
   I001
   I002 

这是可能的,如果是这样的话怎么样? JOIN似乎无法正常工作,UNION除非在我的实际数据库设计中有必要做的事情。关于什么会起作用的任何想法?

3 个答案:

答案 0 :(得分:4)

看起来像你想要的是以下查询:

select ItemID
from Table1
union
select ItemID
from Table2

union消除了重复的行。如果您想保留副本,请使用union all

答案 1 :(得分:3)

简单方法(假设MySQL由于mysql标记):

   select ItemId as ItemId
   from Table1 as t1
   union 
   select ItemId  as ItemId
   from Table2 as t2

DEMO HERE

如果您真的希望将*作为结果的一部分,请使用以下代码(模拟左外连接):

 select IFNULL(t.ItemId1, t.ItemId2), case when t.ItemId1 = t.ItemId2 then '*' else '' end as star
 from(
  select t1.ItemId as ItemId1, t2.ItemId  as ItemId2 FROM Table1  t1
  left join Table2  t2 on t1.ItemId = t2.ItemId
  union
  select t1.ItemId as ItemId1, t2.ItemId as ItemId2  FROM Table1  t1
  right join Table2  t2 on t1.ItemId = t2.ItemId
) as t

2ND DEMO HERE

答案 2 :(得分:0)

假设delphi支持完全外连接......不要认为mySQL会...

这将从生成的外连接中获取第一个非空值并使用它。如果在两个表中都找到了值a' *'连接到值的末尾,否则它将保持不变。

SELECT concat(coalesce(T1.itemID, T2.itemID), 
       case when t1.itemID=t2.itemID then ' *' else '' end) as ItemID
FROM table1 T1
FULL OUTER JOIN table2 T2
 on T1.ItemID = T2.ItemID

如果不是,我们可以使用穷人的外部联接...左边连接t1 - > t2然后联合T2 - > t1类似......

SELECT concat(coalesce(T1.itemID, T2.itemID), 
       case when t1.itemID=t2.itemID then ' *' else '' end) as ItemID
FROM table1 T1
LEFT JOIN table2 T2
 on T1.ItemID = T2.ItemID

UNION 

SELECT concat(coalesce(T1.itemID, T2.itemID), 
       case when t1.itemID=t2.itemID then ' *' else '' end) as ItemID
FROM table2 T2
LEFT JOIN table1 T1
 on T1.ItemID = T2.ItemID