我有一个PDO语句,它从一些不同的表中选择一些数据。虽然,我不确定如何从另一个表中选择数据:
SELECT
c.forum_id as category_id,
c.forum_name as category_name,
t.forum_id as id,
t.forum_name as name,
t.forum_desc as description,
(SELECT COUNT(*) FROM forum_topics WHERE forum_id=t.forum_id AND topic_deleted=0) as topics_count,
(SELECT COUNT(*) FROM forum_posts WHERE forum_id=t.forum_id AND post_deleted=0) as posts_count,
(SELECT COUNT(*) FROM forum_posts WHERE topic_id=lp.topic_id AND post_deleted=0) as last_post_count,
lp.topic_id as last_post_topic_id,
lp.topic_title as last_post_topic_title,
lp.post_time as last_post_time,
lp.username as last_post_username
FROM forum_cats as t
JOIN forum_cats as c on c.forum_id = t.forum_type_id
left join (
SELECT
ft.topic_id,
ft.title as topic_title,
tmp.post_time,
u.username,
fp.forum_id
FROM
forum_posts fp
join forum_topics ft on ft.topic_id = fp.topic_id
join users u on u.id = fp.userid
join (
select forum_id, max(`post_time`) `post_time`
from forum_posts fp
where fp.post_deleted = 0
group by forum_id
) as tmp on (fp.forum_id = tmp.forum_id and fp.post_time = tmp.post_time)
where post_deleted = 0 and ft.topic_deleted = 0
) as lp on lp.forum_id = t.forum_id
where t.forum_active = 1 and c.forum_active = 1
order by category_id, t.forum_id
");
现在,我想选择avatar
列。users
其中username
。users
= last_post_username
(avatar
列,来自users
表格。
我绝对不知道从哪里开始。我应该这样说吗?
(SELECT avatar FROM users WHERE username=last_post_username)
虽然不起作用。
感谢任何帮助。
答案 0 :(得分:0)
你已经拥有" last_post_username"基于联接为" u.id = fp.userid"。您只需要检索" lp.avatar"
以下是我的回答:
SELECT
c.forum_id as category_id,
c.forum_name as category_name,
t.forum_id as id,
t.forum_name as name,
t.forum_desc as description,
(SELECT COUNT(*) FROM forum_topics WHERE forum_id=t.forum_id AND topic_deleted=0) as topics_count,
(SELECT COUNT(*) FROM forum_posts WHERE forum_id=t.forum_id AND post_deleted=0) as posts_count,
(SELECT COUNT(*) FROM forum_posts WHERE topic_id=lp.topic_id AND post_deleted=0) as last_post_count,
lp.topic_id as last_post_topic_id,
lp.topic_title as last_post_topic_title,
lp.post_time as last_post_time,
lp.username as last_post_username,
lp.avatar
FROM forum_cats as t
JOIN forum_cats as c on c.forum_id = t.forum_type_id
left join (
SELECT
ft.topic_id,
ft.title as topic_title,
tmp.post_time,
u.username,
u.avatar,
fp.forum_id
FROM
forum_posts fp
join forum_topics ft on ft.topic_id = fp.topic_id
join users u on u.id = fp.userid
join (
select forum_id, max(`post_time`) `post_time`
from forum_posts fp
where fp.post_deleted = 0
group by forum_id
) as tmp on (fp.forum_id = tmp.forum_id and fp.post_time = tmp.post_time)
where post_deleted = 0 and ft.topic_deleted = 0
) as lp on lp.forum_id = t.forum_id
where t.forum_active = 1 and c.forum_active = 1
order by category_id, t.forum_id
");