我在mysql中有两个表。例如,第一个具有用户数据,第二个具有属性数据。 我想从表1中选择每个用户,并从表2中获取他的所有属性。
e.g。 表1:
| userid | name |
| 1 | John |
| 2 | Billie |
表2:
| userid | attribute |
| 1 | male |
| 1 | taxi driver |
| 1 | 45 years |
| 2 | female |
| 2 | clerk |
所以我想得到我的mysql结果:
| userid | name | attributes |
| 1 | John | male, taxi driver, 45 years |
| 2 | Billie | female, clerk |
我绝对没有想法,如何巩固这些属性(甚至可能是逗号分隔)。我也在这里搜索过,但没有发现类似的东西。
你能帮忙吗?感谢答案 0 :(得分:2)
我认为您可以为此使用GROUP_CONCAT。
SELECT userid, name, GROUP_CONCAT(attribute) as attributes
FROM table1
INNER JOIN table2 ON table1.userid = table2.userid
GROUP BY table2.userid
请参阅此SQLFiddle示例:http://sqlfiddle.com/#!9/fd365d4/6/0
答案 1 :(得分:0)
;with SampleDataR as
(
select *, ROW_NUMBER() over (partition by title, subtitle order by value) rownum
from test12
)
select distinct title, subtitle,(
select value
+ case when s1.rownum = (select MAX(rownum) from SampleDataR where title = s1.title and subtitle = s1.subtitle)
then '' else ',' end from SampleDataR s1
where s1.title = s2.title and s1.subtitle = s2.subtitle
for xml path(''),type).value('(.)[1]','varchar(max)') csvList
from SampleDataR s2