Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 具有不同列的SQL联合_Mysql_Sql_Workbench - Fatal编程技术网

Mysql 具有不同列的SQL联合

Mysql 具有不同列的SQL联合,mysql,sql,workbench,Mysql,Sql,Workbench,您好,我不确定问这个问题的最佳方式,但我已经成功运行了两个SQL查询,分别检索我正在搜索的结果。然而,我想将这两个结果基本上附加/连接在一起,但由于我对SQL相当陌生,我不确定使用哪种方法。我尝试了Union,但这不起作用,因为两个表都需要相同数量的列。还尝试了左连接,但这给了我一个一般语法错误(可能是代表我,我也是新手) 第一个问题 SELECT prac.healthPracID, prac.firstName, prac.surname FROM healthpractitioners a

您好,我不确定问这个问题的最佳方式,但我已经成功运行了两个SQL查询,分别检索我正在搜索的结果。然而,我想将这两个结果基本上附加/连接在一起,但由于我对SQL相当陌生,我不确定使用哪种方法。我尝试了Union,但这不起作用,因为两个表都需要相同数量的列。还尝试了左连接,但这给了我一个一般语法错误(可能是代表我,我也是新手)

第一个问题

SELECT prac.healthPracID, prac.firstName, prac.surname
FROM healthpractitioners as prac
第二个问题

select count(treatmentrecords.nickname) as patients
from treatmentrecords
group by treatmentrecords.healthpracID;
或者,有人可以帮我重写这些语句,以便在一个查询中获得相同的结果。我以前尝试过类似的方法,并做了以下工作(但没有产生正确的输出-似乎有相同数量的患者,所有的名字和姓氏只是健康医生表中的第一个,但重复):

提前谢谢,如果这已经被张贴了,很抱歉,我很困惑,不知道如何最好地搜索它

PS Im在Windows上运行MySQL Workbench,如果这有什么区别的话。
Sam.

您的第二次尝试是在正确的轨道上,但是它缺少一个连接条件,并且您应该按照
healthpractioners#healthPracID
进行分组

SELECT
    p.healthPracID,
    p.firstName,
    p.surname,
    COUNT(t.healthPracID) AS num_patients
FROM healthpractioners p
LEFT JOIN treatmentrecords t
    ON p.healthPracID = t.healthPracID
GROUP BY
    p.healthPracID;
这个答案假设
healthPracID
healthpraciners
中的主键,或者它有一个唯一的索引。在这种情况下,我们可以通过
healthPracID
进行分组。如果没有,那么我们将不得不使用以下
分组依据

GROUP BY
    p.healthPracID,
    p.firstName,
    p.surname
请尝试以下操作:

SELECT prac.healthPracID, prac.firstName, prac.surname,
count(treat.nickname) as patients
FROM healthpractitioners as prac LEFT JOIN treatmentrecords AS treat
ON prac.healthPracID = treat.healthPracID 
GROUP BY prac.healthPracID, prac.firstName, prac.surname

使用两个表中的公共字段执行
左联接
,然后对所需的列使用聚合函数
计数
,其余列在
分组依据中指定

是的,我这样做了,效果很好!!非常感谢!!healthPracID是主键,所以要理解您所做的只是在healthpracitioners表中添加一个连接条件并按healthPracID分组,而不是在treatmentrecords表中按healthPracID分组?还有一个问题,当使用左联接时,必须为相同的列指定条件?这到底是为什么?我有点好奇为什么。是的,这就是我真正改变的一切。您遇到的最大问题是加入订单。再次感谢您,如何将问题标记为已解决/最佳答案?
SELECT prac.healthPracID, prac.firstName, prac.surname,
count(treat.nickname) as patients
FROM healthpractitioners as prac LEFT JOIN treatmentrecords AS treat
ON prac.healthPracID = treat.healthPracID 
GROUP BY prac.healthPracID, prac.firstName, prac.surname