简体   繁体   English

MySQL查询联接两个表

[英]Mysql Query Join two tables

I have two simple tables about one about dog breeds and one with dog names. 我有两个简单的表格,其中一张关于狗的品种,另一张关于狗的名字。

Breeds:

DogId  DogBreed                         

   1    boxer                            
   2     Lab                              
   3    Sheppard

Names:

DogId   DogName
   1      Max
   1      duke
   2      Jack
   2      Socks
   3      Lassie   

The results I am looking for is 我正在寻找的结果是

boxer - duke, max
Lab- jack, socks
Sheppard- Lassie

I have tried Inner joins, but I really can't figure this out, it seems so easy. 我已经尝试了内部联接,但是我真的无法弄清楚,这似乎很容易。 Any help would be very welcome 任何帮助将非常欢迎

Inner queries will slow down the performance (because of higher execution time) if you have large number of records. 如果您有大量记录,内部查询会降低性能(由于执行时间更长)。

Optimised SQL Query: 优化的SQL查询:

SELECT b.DogBreed,GROUP_CONCAT(n.DogName) FROM Breeds b 
LEFT JOIN `Names` n ON n.DogId=b.DogId
GROUP BY n.DogId

You can use GROUP_CONCAT 您可以使用GROUP_CONCAT

Try, 尝试,

Select 
    b.dogbreed,
    GROUP_CONCAT(
        DISTINCT n.dogname
        ORDER BY n.dogname ASC SEPARATOR ', '
    ) dognames
from breeds b
join names n on n.dogid = b.dogid
group by b.dogbreed

Hope this will help you 希望这个能对您有所帮助

 SELECT b.dogbreed , (SELECT GROUP_CONCAT(DogName) 
FROM NAMES WHERE DogId = b.DogId ) AS DogNames FROM Breeds b

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

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