数据库表结构如下:
CREATE TABLE `ds_settle_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL COMMENT '用户id',
`pid` int(11) NOT NULL COMMENT '推荐人id,0是推荐人是本人非0为上级推荐人',
`user_name` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `ds_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`user_name` varchar(40) NOT NULL COMMENT '用户名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
需求:当pid的值为0是推荐人为自己,需要执行查询条件ds_settle_user表user_id等于ds_user表id链表查询,当pid不等于0是查询ds_settle_user表pid等于ds_user表id
数据样本:
sql语句核心代码:
SELECT
b.*,a.user_name AS referee
FROM
ds_user AS a
JOIN ds_settle_user AS b ON (
CASE b.pid
WHEN 0 THEN
a.id = b.user_id
ELSE
a.id = b.pid
END
)
效果图如下:
|
|