您可以使用group_concat:
SELECt a.name, a.city, a.address, a.abbrv, b.urltype, group_concat(b.url SEPARATOR ' ')FROM jos__universityTBL as a LEFT JOIN jos__university_urlTBL as b on b.universityID = a.ID WHERe a.stateval = 'CA'GROUP BY a.name, a.city, a.address, a.abbrv, b.urltype
在SQL中很难生成动态列。尽可能查看是否可以将其移至客户端。如果不是,则可以在子查询中添加行号,并为每个行号分配自己的列。这是一个表稍有不同的示例:
drop table if exists Universities;drop table if exists Urls;create table Universities ( id int auto_increment primary key, Name varchar(50));create table Urls ( id int auto_increment primary key, UniversityId int, Url varchar(50));insert into Universities (name) values ('USC'), ('SJSU');insert into Urls (UniversityId, Url) values (1,'http://a/'), (1,'http://b/'), (2,'http://c/'), (2,'http://d/'), (2,'http://e/');SELECT Name, group_concat(case RowNr when 1 then Url end) as FirstCol, group_concat(case RowNr when 2 then Url end) as SecondCol, group_concat(case RowNr when 3 then Url end) as ThirdColFROM ( SELECt u.Name , l.Url , (@i := case when @LastUni = u.Name then @i + 1 else 1 end) as RowNr , @LastUni := u.name FROM Universities u JOIN Urls l ON u.id = l.UniversityId JOIN (SELECT @i := 0, @LastUni := '') init) subqueryGROUP BY Name;打印:
SJSU http://c/ http://d/ http://e/USC http://a/ http://b/ NULL



