二个表查询数据,MYSQL怎么写语句

二个表查询数据,MYSQL如何写语句。

有二张表,一张叫ta,一张叫tb。它们有uid与sdate这二个字段相对应的。

现在有这三种情况,需要显示记录集:

如果ta中在某个日期里面有记录,但是tb中没有,也要显示记录集,如果ta表中在某个日期下面,没有记录,而tb有,这个记录也要显示。如果ta表与tb表都有数据,这个也要显示出来。并且二个表中的uid一定是相同的,这个SQL语句如何写呢?

我是这样写的,但是数据不对,有些字段没有值的,也显示值了,并且重复。

SELECT a.uid, a.idate,a.step, a.eatcalory,a.actcalory,b.isj,b.isc FROM 

ta a, tb b WHERE a.uid = b.uid AND a.uid =845444

请高手帮一下忙,加了DISTINCT 这个也是一样的结果。


SQL code

SELECT a.uid, a.idate,a.step, a.eatcalory,a.actcalory,b.isj,b.isc FROM  

ta a left join  tb b on a.uid = b.uid where a.uid =845444

union 

SELECT a.uid, a.idate,a.step, a.eatcalory,a.actcalory,b.isj,b.isc FROM  

ta a right join  tb b on a.uid = b.uid where a.uid =845444


(不要高估你的汉语表达能力或者我的汉语理解能力)
建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
 
1. 你的 create table xxx .. 语句
2. 你的 insert into xxx ... 语句
3. 结果是什么样,(并给以简单的算法描述)
4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
 
这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。



SQL code
select 
  isnull(a.uid,b.uid) as uid,
  isnull(a.idate,b.idate) as idate,
  isnull(a.step,0) as step,
  isnull(a.eatcalory,0) as eatcalory,
  isnull(a.actcalory,0) as actcalory,
  isnull(b.isj,0) as isj,
  isnull(b.isc,0) as isc
from a
full join b on a.uid=b.uid and a.idate=b.idate


select uid,idate,step,sum(eatcalory),sum(actcalory),sum(isj),sum( isc)
form (
select uid,idate,step,eatcalory,actcalory,0 as isj,0 as isc
from a
union all
select uid,idate,0,0,0, isj, isc
from b
) t
group by uid,idate
二个表查询数据,MYSQL怎么写语句

相关文章:

你感兴趣的文章:

标签云: