有没有办法在子查询中选择多个列?我想从username
表(第3行和第4行)中选择两列dateline
和posts
,我不想创建两个单独的子查询。或者有没有办法通过加入来做到这一点?
SELECT `topics`.`id` AS `id`, `title`, `unique_views`, `tags`.`name` AS `name`, `bg_color`, `text_color`,
`username`, `avatar`, `color`,
(select `username` from `posts` where `topic_id` = `topics`.`id` order by `dateline` desc) as lastpost_username,
(select `dateline` from `posts` where `topic_id` = `topics`.`id` order by `dateline` desc) as lastpost_dateline,
(select `vote` from `topic_votes` where `topic_id` = `topics`.`id` and `voter_id` = :voter_id) as user_vote,
(select count(*) from `topic_votes` where `topic_id` = `topics`.`id` and `vote` = 1) -
(select count(*) from `topic_votes` where `topic_id` = `topics`.`id` and `vote` = -1) AS vote_sum
FROM `topics`
INNER JOIN `tags` ON `tags`.`id` = topics.`tag_id`
INNER JOIN `users` ON `topics`.`poster_id` = `users`.`id`
INNER JOIN `user_groups` ON `users`.`group_id` = `user_groups`.`id`
INNER JOIN `posts` ON `posts`.`topic_id` = `topics`.`id`
ORDER BY `topics`.`dateline` DESC
LIMIT 50
答案 0 :(得分:0)
你可以这样做。你可以加入派生表,但我不能测试:
SELECT `topics`.`id` AS `id`, `title`, `unique_views`, `tags`.`name` AS `name`, `bg_color`, `text_color`,
`username`, `avatar`, `color`,
new_table.lastpost_username,
new_table.lastpost_dateline,
(select `vote` from `topic_votes` where `topic_id` = `topics`.`id` and `voter_id` = :voter_id) as user_vote,
(select count(*) from `topic_votes` where `topic_id` = `topics`.`id` and `vote` = 1) -
(select count(*) from `topic_votes` where `topic_id` = `topics`.`id` and `vote` = -1) AS vote_sum
FROM `topics
LEFT JOIN (
select `username`,`dateline` FROM `posts` ORDER BY `dateline` DESC
) AS new_table ON `new_table`.`topic_id` = `topics`.`id`
INNER JOIN `tags` ON `tags`.`id` = topics.`tag_id`
INNER JOIN `users` ON `topics`.`poster_id` = `users`.`id`
INNER JOIN `user_groups` ON `users`.`group_id` = `user_groups`.`id`
INNER JOIN `posts` ON `posts`.`topic_id` = `topics`.`id`
ORDER BY `topics`.`dateline` DESC
LIMIT 50
答案 1 :(得分:0)
注意:适用于Postgresql 。
我没有为postgresql找到类似的问题。我希望这对双方都有帮助|
您可以为此使用LATERAL
伪代码
无侧向
SELECT *, T1.ID, S1.name from (
select *, (select id from mysubquery) as TID from myTable
) AS T1
LEFT JOIN subquery S1 ON (T1.TID=S1.ID) -- for take name
侧面
select *, TID.id, TID.name
from myTable,
LATERAL (select id, name from mysubquery) as TID