mysql - 使用两个左连接mysql时出现重复值

标签 mysql

在正负场中,值相同。请帮助解决这个问题...

   SELECT 
    name,
    COUNT(p.service_provider_id) as positive,
    COUNT(n.service_provider_id) as negative


 FROM tablesite

    LEFT JOIN action p
    ON tablesite.id_user=p.service_provider_id
    AND p.vote !='' AND p.customer_comment ='' //equal

    LEFT JOIN action n
    ON tablesite.id_user=n.service_provider_id
    AND n.vote !='' AND n.customer_comment !='' //unequal
    GROUP BY name

最佳答案

说明目的

架构

-- drop table t1;
create table t1
(   id int auto_increment primary key,
    theName varchar(10) not null,
    birthDate date not null
);

-- drop table t2;
create table t2
(   id int auto_increment primary key,
    refId int not null,
    comments varchar(1000) not null, -- your choice, but this is my demo :)
    key(refId)
);

insert t1 (theName,birthDate) values ('cat','2014-11-01'),('mouse','2014-12-21');

insert t2(refId,comments) values
(1,"i like this cat"),(1,"he is fury"),(1,""),
(2,"more cheese");

查询

select t1.id,t1.theName,t1.birthDate,
SUM(CASE WHEN t2.comments!="" THEN 1 ELSE 0 END) commentCount,
SUM(CASE WHEN t2.comments="" THEN 1 ELSE 0 END) notAcommentCount
from t1
join t2
on t2.refId=t1.id
group by t1.id,t1.theName,t1.birthDate;

+----+---------+------------+--------------+------------------+
| id | theName | birthDate  | commentCount | notAcommentCount |
+----+---------+------------+--------------+------------------+
|  1 | cat     | 2014-11-01 |            2 |                1 |
|  2 | mouse   | 2014-12-21 |            1 |                0 |
+----+---------+------------+--------------+------------------+

这就是您想要的吗?

<小时/>

答案:

SELECT 
tablesite.name,
SUM(CASE WHEN action.vote !="" AND action.customer_comment ="" THEN 1 ELSE 0 END) مثبت,
SUM(CASE WHEN action.vote !="" AND action.customer_comment !="" THEN 1 ELSE 0 END) منفی

FROM tablesite

JOIN action
ON tablesite.id_user=action.service_provider_id
group by tablesite.name 

关于mysql - 使用两个左连接mysql时出现重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33744966/

相关文章:

php - 通过 PHP 中的链接更新 MySQL 数据库

mysql - 如何使用 rails 将 excel 文件导入 mysql?

MySQL 使用了不正确的索引。为什么?

php - 使用 php 发送带有多个复选框的电子邮件

mysql - 如何查询MySQL中包含空字符的字段

mysql - 为什么使用 MyISAM 引擎而不是 InnoDB 创建的默认 'mysql' 数据库?

mysql - 调试mysql sproc, 'NULL'附近语法正确

php - mySQL 或 MSSQL 最适合拍卖网站?

php - 循环遍历结果是否为 NULL 值返回空字符串?

java - 在mysql数据库中插入日期