如何结合两个具有不同列数的表?

时间:2014-07-09 13:32:20

标签: sql

这是我的疑问。

select id,sender_id,receiver_id,date_added,subject,book_id,message from trading_message where (receiver_id=1132 or receiver_id=66) and (sender_id=1132 or sender_id=66)
union
select id,sender_id,receiver_id,date_added,message,'A' as subject,'B' as book_id from personal_message where (receiver_id=1132 or receiver_id=66) and (sender_id=1132 or sender_id=66) order by date_added asc

我得到了这样的错误。 未知栏' A'在' where子句'

请帮忙。

4 个答案:

答案 0 :(得分:1)

这适用于 MYSQL

联合中的重要规则之一:字段数必须相等。

select id,sender_id,receiver_id,date_added,message, subject,book_id, from trading_message where (receiver_id=1132 or receiver_id=66) and (sender_id=1132 or sender_id=66)
union
select id,sender_id,receiver_id,date_added,message,'','' from personal_message where (receiver_id=1132 or receiver_id=66) and (sender_id=1132 or sender_id=66) order by date_added asc

注意:您的第二个子查询中不需要别名,引擎会从您的第一个选择结果中获取字段名

答案 1 :(得分:1)

我为MS Sql Server运行了这个。我认为其中一个问题是' B'正在以book_id的形式返回,我猜测是联合查询的第一部分中的int。作为" TheOneWhoPrograms"提到的列也必须按顺序排列。

Create Table dbo.trading_message
(
 id int
 ,sender_id int
 ,receiver_id int
 ,date_added datetime
 ,subject varchar(100)
 ,book_id int
 ,message varchar(1000)
)

Create Table dbo.personal_message
(
 id int
 ,sender_id int
 ,receiver_id int
 ,date_added datetime
 ,message varchar(1000)
)

select 
 id
 ,sender_id
 ,receiver_id
 ,date_added
 ,subject
 ,book_id -- <- I *guessing* this is an int
 ,message 
from trading_message 
where (receiver_id=1132 or receiver_id=66) 
 and (sender_id=1132 or sender_id=66)

union

select 
 id
 ,sender_id
 ,receiver_id
 ,date_added
 ,'A' as subject
 ,0 as book_id -- <- Changed this from 'B' to zero
 ,message
from personal_message 
where (receiver_id=1132 or receiver_id=66) 
 and (sender_id=1132 or sender_id=66) 

order by date_added asc

上面的列(或更具体地说)列数据类型具有相同的顺序

答案 2 :(得分:0)

select id,sender_id,receiver_id,date_added,subject,book_id,message from trading_message where (receiver_id=1132 or receiver_id=66) and (sender_id=1132 or sender_id=66)
union
select id,sender_id,receiver_id,date_added,'A', 'B', null from personal_message where (receiver_id=1132 or receiver_id=66) and (sender_id=1132 or sender_id=66) order by date_added asc

尝试一下..我认为我按照正确的顺序匹配你的列,每个都有合适的数量......

答案 3 :(得分:-1)

请尝试设置mysql变量而不是char&#39; A&#39;像

  

@ var1 AS subject

而不是

  

&#39; A&#39;作为主题