[英]Select multiple columns in subquery
有没有一种方法可以选择子查询中的多个列? 我想从posts
表(第三行和第四行)中选择两列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
您可以这样做。 您可以加入派生表,但我不能testet:
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
注意 : 对于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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.