4个表的复杂联合查询,求助!
有4个表,结构分别如下:
atten表结构和数据:
id uid oid
1 1 2
2 1 3
3 1 4
4 2 3
5 2 4
说明:uid为一个用户的ID,oid为他感兴趣的用户ID
user表结构和数据:
id name
1 tom
2 jone
3 lily
说明:该表为用户表,保存用户id和姓名
order表结构和数据:
id uid title time
1 1 abcd 1331554986
2 1 123123 1331555000
3 2 ashousdf 1331554900
4 2 hujhljh 1331560000
说明:该表保存用户所有的订单标题及时间
join表结构和数据:
id uid orderid time
1 2 1 1331554986
2 3 1 1331554900
3 2 2 1331555000
现在要求返回atten表中用户id(uid)为1的用户感兴趣的所有用户的用户信息,包括感兴趣用户最新的订单(order表)以及最新参与的订单(join)【此处需要返回参与的订单的标题】。
请教大侠,这样的SQL要如何写?如果不能用联合查询返回结果,该怎么处理效率高些?膜拜中。。THANKS!
------解决方案--------------------
select u.id,u.name,o.title,j.*
from atten a inner join user u on a.oid=u.id
left join (select * from `order` x where not exists (select 1 from `order` where uid=x.uid and time>x.time)) o on u.id=o.uid
left join (select * from `join` y where not exists (select 1 from `join` where uid=y.uid and time>y.time)) j on u.id=j.uid
where a.uid=1
------解决方案--------------------SELECT * FROM `user` a1 INNER JOIN (
SELECT uid,MAX(IF(`type`=1,a.`order_title`,'')),MAX(IF(`type`=1,a.`order_id`,'')),
MAX(IF(`type`=2,a.`order_title`,'')),MAX(IF(`type`=2,a.`order_id`,''))
FROM `DYNAMIC` a WHERE NOT EXISTS(SELECT 1 FROM `DYNAMIC` WHERE a.`uid`=`uid`
AND a.`type`=`type` AND a.`time`<`time`)
GROUP BY a.`uid`) b1 ON a1.`id`=b1.uid
------解决方案--------------------CREATE TABLE `joinc` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL,
`orderid` int(11) NOT NULL,
`time` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
/*Data for the table `joinc` */
insert into `joinc`(`id`,`uid`,`orderid`,`time`) values (1,2,1,1331554986),(2,3,1,1331554900),(3,2,2,1331555000);
join不能用,所以改成joinc了