MySQL - 如何使用LEFT JOIN两次?

时间:2017-03-25 07:44:17

标签: mysql database

我有2张桌子,董事会和投票。

create table board (
id int unsigned not null primary key auto_increment,
type varchar(10) not null,
article_id int unsigned,
title varchar(255) not null,
content text not null);

create table vote (
no int unsigned not null primary key auto_increment,
id int unsigned not null
voter_email varchar(255));

在电路板表中,存储了两种类型的数据,文章和回复,只有回复类型有一个article_id。
所以我可以使用下面的查询计算每篇文章的回复数量。

select b.id, b.title, b.content, b2.reply 
from board b left join 
(select article_id, count(id) as reply from board 
where article_id is not null group by article_id) 
b2 on b2.article_id = b.id;

+----+-------+---------+-------+
| id | title | content | reply |
+----+-------+---------+-------+
| 10 | uu    | uuu     |  NULL |
| 12 | eee   | eeee    |     4 |
+----+-------+---------+-------+

我可以使用下面的查询计算每篇文章的投票数量。

select id, count(*) as vote from vote group by id; 
+----+------+
| id | vote |
+----+------+
| 12 |    1 |
+----+------+

我现在正试图将两个结果合并为一个。

我该怎么做?
我期望的结果是:

+----+-------+---------+-------+------+
| id | title | content | reply | vote |
+----+-------+---------+-------+------+
| 10 | uu    | uuu     |  NULL | NULL |
| 12 | eee   | eeee    |     4 |    1 |
+----+-------+---------+-------+------+

4 个答案:

答案 0 :(得分:0)

再做一次left join

select b.id, b.title, b.content, b2.reply 
from board b 
left join (
    select article_id, count(id) as reply 
    from board 
    where article_id is not null 
    group by article_id) b2 on b2.article_id = b.id
left join (
    select id, count(*) as vote 
    from vote 
    group by id) AS v on v.id = b.id

答案 1 :(得分:0)

最后添加另一个left join

select b.id, b.title, b.content, b2.reply, v.vote
from board b
left join (
    select article_id, count(id) as reply
    from board
    where article_id is not null
    group by article_id
    ) b2 on b2.article_id = b.id
left join (
    select id, count(*) as vote
    from vote
    group by id
    ) v on b.id = v.id;

答案 2 :(得分:0)

向您展示示例和您的架构,您应该使用左连接和分组

background-image: url('/img/cloader.gif') no-repeat center top;

答案 3 :(得分:-1)

你可以使用子查询而不是像这样的连接:

select b.id, 
        b.title, 
        b.content, 
        (select count(*) from board as b2 where article_id = b2.id) as reply, 
        (select count(*) from vote where id = b.id) as votes
from board b ;

为了保持系统的性能,您应该添加一个索引,一个在votes.id上,一个在on.article_id

注意:由于我现在不在我的电脑附近,因此无法测试此查询,因此您可能需要调整它;)

我希望这会有所帮助:)