2016-04-24 95 views
0

有沒有辦法在子查詢中選擇多個列?我想從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 
+0

我會重新開始,與適當的CREATE和INSERT語句和所需的結果 – Strawberry

回答

0

你可以這樣做。你可以加入派生表,但我不能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