有下面两个表
desk表结构
desk_id left_id right_id
1 3 null
2 null 2
3 1 2
user表结构
user_id name
1 小明
2 小红
3. 小丽
left_id 与 user_id 对应
想得到这样一个结果, 把left_id 替换成 white, right_id 替换成 black
desk_id color name
1 white 小丽
2. black 小红
3 white 小明
3. black 小红
我的做法是两条sql语句查询, 然后再把结果合并在一起
select desk_id, white as color, name from desk inner join user on user_id = left_id where left_id is not null;
select desk_id, black as color, name from desk inner join user on user_id = left_id where right_id is not null;
能不能只用一条sql语句得到呢 , 或者还有其它更好的办法 ?
两个问题。
第一,你需要笛卡尔积join,才能在两个3行的表取出3行以上的记录
第二,你需要IS NULL的为A,IS NOT NULL的为B,所以需要if语句,在mysql里是CASE语法。
方便各位调试
体会一下楼主的脑洞
最终还是成功了
调试了60次。。