有没有办法在子查询中选择多个列?我想从 posts
表(第 3 行和第 4 行)中选择两列 username
和 dateline
,并且我不想创建两个列单独的子查询。或者有没有办法通过连接来做到这一点?
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
最佳答案
注意:对于 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
关于mysql - 在子查询中选择多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36820535/