简体   繁体   English

在MYSQL中联接多个表

[英]Joining multiple tables in MYSQL

Here's an example of the kind of join I'm trying to accomplish. 这是我尝试完成的那种连接的示例。 http://sqlfiddle.com/#!2/aab00/3 . http://sqlfiddle.com/#!2/aab00/3

You can see that there are records (Name2, Name3) that satisfy the WHERE clause but do not show up. 您会看到有些记录(Name2, Name3)满足WHERE子句但没有显示。 Also the record for Name1 that shows up isn't accurate. 另外,显示的Name1记录也不正确。

You should do the aggregation before the join s: 您应该在join之前进行聚合:

SELECT t3.PersonName AS Name,
       COALESCE(t1.NumberOfCars, 0) AS NumberOfCars,
       COALESCE(TMobile, 0) AS TMobileConnections,
       COALESCE(ATT, 0) AS ATTConnections
FROM Table3 t3 LEFT OUTER JOIN
     Table1 t1
     ON t3.PersonSSN = t1.PersonSSN and t1.State = 'FL' LEFT OUTER JOIN
     (select t2.PersonSSN, t2.state,
             max(t2.Carrier = 'T Mobile') as TMobile,
             max(t2.Carrier = 'AT&T') as ATT
      from Table2 t2
      group by t2.PersonSSN, t2.state
     ) t2
     ON t3.PersonSSN = t2.PersonSSN and t2.State = 'FL';

You could also do the filtering by state in the subqueries, but this works for this query. 您也可以在子查询中按状态进行过滤,但这适用于此查询。

Note that I changed all the double quotes to single quotes. 请注意,我将所有双引号更改为单引号。 Always use single quotes for string and date constants -- that is standard SQL. 始终对字符串和日期常量使用单引号-这是标准SQL。 Use double quotes or backticks for quoting identifiers, when needed. 必要时,请使用双引号或反引号将标识符引起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM