Pasteid
字段是一个有时为空的字段,当它已满时将引用发布表,发布表通过Userid
字段连接到用户表。
select `posts`.`id` as `pid`, `posts`.`media` as `pmedia`, `posts`.`created_at` as `pcreated_at`, `posts`.`txt`, `users`.`media` as `umedia`, `users`.`id`, `users`.`name` as `name`, `users`.`username`, `posts`.`options`, `posts`.`likes`, `posts`.`comments`, `posts`.`copyid`, `posts`.`pasteid`, `u`.`name` as `replayname`, `u`.`name` as `replayuser`
from `posts`
inner join `usersq` on `users`.`id` = `posts`.`userid`
inner join `posts` as `p` on `posts`.`pasteid` = `p`.`id`
inner join `users` as `u` on `u`.`id` = `p`.`userid`
where (`posts`.`block` = 0 and `users`.`view` = 1) and `users`.`status` not in (1, 3)
order by `posts`.`created_at` desc
limit 30
实际上,我们想知道帖子是否已被复制以及从哪个副本复制。
上面的代码的问题在于,它仅包含Pasteid
字段必须填写的记录,如果为空,则不包含输出
后桌 id txt媒体pasteid用户ID 1 eee 1.jpg 1 2 rrr 1 3 eee 1.jpg 1 2
用户表 身份证名 1阿里 2个插孔
如您所见,插孔是从后面复制的。现在,我需要从用户表中获取阿里的名字,并将其放在replayname字段中
答案 0 :(得分:0)
只需使用LEFT JOIN
而不是INNER JOIN
。
LEFT JOIN
将返回左表中的所有记录,即使它们在右表中不匹配也是如此。
select `posts`.`id` as `pid`, `posts`.`media` as `pmedia`, `posts`.`created_at` as `pcreated_at`, `posts`.`txt`, `users`.`media` as `umedia`, `users`.`id`, `users`.`name` as `name`, `users`.`username`, `posts`.`options`, `posts`.`likes`, `posts`.`comments`, `posts`.`copyid`, `posts`.`pasteid`, `u`.`name` as `replayname`, `u`.`name` as `replayuser`
from `posts`
inner join `usersq` on `users`.`id` = `posts`.`userid`
left join `posts` as `p` on `posts`.`pasteid` = `p`.`id`
left join `users` as `u` on `u`.`id` = `p`.`userid`
where (`posts`.`block` = 0 and `users`.`view` = 1) and `users`.`status` not in (1, 3)
order by `posts`.`created_at` desc
limit 30