[英]MySQL GROUP BY FIND_IN_SET
I have a table with that looks like this: 我有一张桌子,看起来像这样:
|id | name | sport |
|---|------|------------------|
|1 | john | kitesurf |
|2 | mike | kitesurf |
|3 | tobi | tennis, kitesurf |
|4 | mat | surf, skate |
|5 | bob | tennis |
How can I get a list with groups by sports that would look like this: 如何获得按运动分组的列表,如下所示:
| sport | name
|-----------|-------
| kitesurf | john
| kitesurf | mike
| kitesurf | tobi
| tennis | tobi
| tennis | bob
| skate | mat
| surf | mat
Is it anyhow doable using just MySQL? 仅使用MySQL是否可行? Thanks for any tip :) 谢谢你的提示:)
You'll need another table that lists each distinct sport. 您将需要另一个表格,其中列出了每种不同的运动。
CREATE TABLE Sports ( sport VARCHAR(10) PRIMARY KEY );
INSERT INTO Sports (sport) VALUES ('kitesurf'), ('tennis'), ('skate'), ('surf');
Then you can join this way: 然后,您可以通过以下方式加入:
SELECT s.sport, n.name
FROM NoOneNamesTheirTableInSqlQuestions AS n
INNER JOIN Sports AS s ON FIND_IN_SET(s.sport, n.sport);
But this is an inefficient query, because the FIND_IN_SET()
cannot use an index. 但这是效率低下的查询,因为FIND_IN_SET()
无法使用索引。
See also my answer to Is storing a delimited list in a database column really that bad? 另请参阅我的答案: 在数据库列中存储分隔列表真的那么糟糕吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.