选择不同的连接多个表 [英] Select distinct join multiple tables

查看:50
本文介绍了选择不同的连接多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MySQL 中有两个长表,它们的形式如下

I have two long tables in MySQL that has the form of the following

Tab1
=========
col1 col2
A    X
B    Y

Tab2
=========
col3 col4
A    dog
A    cat
A    dog
B    tree
B    tree
B    bush

我想为 Tab1 的每一行检索 Tab2 的不同值,其中 col1=col3,这样输出看起来像

I'd like to retrieve for each row of Tab1 the distinct values of Tab2 where col1=col3, such that the output looks something like

   Col1   Col4
    A    (dog,cat)
    B    (tree,bush)

我尝试了 SELECT DISTINCTJOIN ON 的组合,但我只是获得了

I tried with combination of SELECT DISTINCT and JOIN ON but I just obtain

dog
cat
tree
bush

我想做的事情可行吗?

推荐答案

SELECT Tab1.col1, GROUP_CONCAT(DISTINCT Tab2.col4) 
FROM Tab1 
INNER JOIN Tab2 ON Tab1.col1 = Tab2.col3
GROUP BY Tab1.col1

请注意结果被截断为 group_concat_max_len 系统变量给定的最大长度,其默认值为 1024".(https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat)

如果您需要大量串联值,则应将此变量设置为更高的值.

You should set this variable to a higher value if you are expecting lots of concatenated values.

这篇关于选择不同的连接多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆