mysql连接不相关的表

时间:2014-06-24 13:14:06

标签: mysql sql

我有2张桌子:

create table words(id int(3) not null primary key auto_increment, name varchar(10) not  null);
insert into words values(null, 'rock');
insert into words values(null, 'rick');
insert into words values(null, 'red');
insert into words values(null, 'black');

create table letters(id int(3) not null primary key auto_increment, name char(1) not null, lang char(2) not null);
insert into letters values(null, 'A', 'en');
insert into letters values(null, 'B', 'en');
insert into letters values(null, 'C', 'es');

现在,要获得所有以'r'开头的单词,我会:     从像'r%';

这样的名字中选择*

如果我想要同时获取lang ='en'的所有字母列表,查询将如何? 我已尝试使用union,但似乎您只能将它用于具有相同列的表。 对于结果列表中的每一行,我想获得id(来自单词),名称(来自单词)以及符合条件lang ='en'的所有字母的连接列表。 我想我需要使用join,但是不能真正弄清楚它会是什么样子。有人能给我一些帮助吗?

1 个答案:

答案 0 :(得分:0)

SELECT  w.id, w.name,
        (
        SELECT  GROUP_CONCAT(name ORDER BY name SEPARATOR ',')
        FROM    letters
        WHERE   lang = 'en'
        )
FROM    words

请注意,此信函列表对于每条记录都是相同的。你真的需要它在数据集中吗?您可能希望考虑在单独的查询中检索它并存储在客户端。

相关问题