日期:2014-05-17  浏览次数:20570 次

=======求个SQL语句=====
本帖最后由 Just_Ask 于 2013-08-13 14:15:51 编辑
需求如下
图片表(pic_table),有如下字段
id,class_id,user_id,
用户关系表(user_relation_table),有如下字段
id,user1_id,user2_id,relation

我现在有个需求:“给一个用户id(user_id假设为1),班级id(class_id假设为2), 要查找属于这个用户班级(class_id=2)的图片,或者他的朋友(relation='friend')的图片”

我现在这么写:

select * from pic_table p, 
(select user1_id as userid from user_relation_table where relation='friend' and user2_id=1
 union select user2_id as userid from user_relation_table where relation='friend' and user1_id=1)
 t1 where p.user_id in (t1.userid) or p.class_id = 2


但是发现,只要这个用户没有好友,即我连接的那张user_relation_table查出来的结果为空的话,整条语句都是没有结果的,即使有class_id=2的图片。
各位高手,我要怎么改?

------解决方案--------------------
会,如果你担心这个,可以改成join:
select a.*
from xxx a left join list b on a.user_id=b.user_id