这是我的SQL问题:
Mysql Database xyz
Table 1
-----------------------
Email Name
1.john@doe.com john
-----------------------
Table 2
-----------------------
Email Color
1.john@doe.com red
2.john@doe.com orange
3.john@doe.com blue
-----------------------
执行查询的正确方法是:
SELECT * FROM ... WHERE table1.email ='john doe'
所以我得到mysql查询结果
[john@doe.com,john,red,orange,blue]
我不好的解决方法:
SELECT Name ,
(SELECT GROUP_CONCAT(Color) As Colors FROM Table2 WHERE Table2.Email = 'john@doe.com')
FROM Table1
WHERE Table1.Email = 'john@doe.com';
答案 0 :(得分:0)
您的解决方案有效,但是更好的方法是使用联接。
SELECT t1.email, t1.name, GROUP_CONCAT(t2.color) AS colors
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON t1.email = t2.email
WHERE t1.email = 'john@doe.com';
这更好,因为您只需要在一个地方指定要查找的电子邮件即可。而且,如果您将WHERE
子句替换为GROUP BY t1.email
,则会得到所有人。