mysql - 在子查询中选择多列

标签 mysql sql

有没有办法在子查询中选择多个列?我想从 posts 表(第 3 行和第 4 行)中选择两列 usernamedateline,并且我不想创建两个列单独的子查询。或者有没有办法通过连接来做到这一点?

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/

相关文章:

mysql - 我可以使用自联接来获取此表吗

sql - ibatis 返回值

sql - 为什么这个查询只选择一行?

php - 使用parent id搜索时如何查询产品?

php - 如何将文件图像存储到 mysql (Codeigniter)

mysql - 无法通过workbench连接到mysql数据库,但可以通过终端登录

php - Laravel 5 Auth 更改表列

sql - SUM 两个 CASE 函数

asp.net - 城市 zip 和州表的最佳数据库设计

SQL 优化