id uid keywords -- --- --- 1 20 corporate 2 20 corporate,business,strategy 3 20 corporate,bowser 4 20 flowers 5 20 battleship,corporate,dungeon
我希望我的输出看起来像是:
20 corporate,business,strategy,bowser,flowers,battleship,dungeon
但我最接近的是:
SELECT DISTINCT uid, GROUP_CONCAT(DISTINCT keywords ORDER BY keywords DESC) AS keywords FROM mytable WHERE uid !=0 GROUP BY uid
输出:
20 corporate,corporate,business,strategy,corporate,bowser,flowers,battleship,corporate,dungeon
有没有人有解决方案?提前谢谢!
答案 0 :(得分:5)
使用纯SQL,您无法按照数据结构的方式进行操作。
没有SQL实现会查看“Corporate”和“Corporate,Business”并将它们视为相同的字符串。因此,明显不起作用。
如果可以控制数据库,
我要做的第一件事就是将数据设置更改为:
id uid keyword <- note, not keyword**s** - **ONE** value in this column, not a comma delimited list
1 20 corporate
2 20 corporate
2 20 business
2 20 strategy
更好的是
id uid keywordId
1 20 1
2 20 1
2 20 2
2 20 3
带有关键字的单独表格
KeywordID KeywordText
1 Corporate
2 Business
否则你需要在代码中按摩数据。
答案 1 :(得分:1)
嗯,您的关键字需要在他们自己的表中(每个关键字一个记录)。然后你就可以做到,因为关键字将正确地组合。
答案 2 :(得分:0)
不确定MySql是否有这个,但是SQL Server有一个RANK()OVER PARTITION BY可以用来为每个结果分配一个等级...这样做只允许你选择Rank 1的那些,并丢弃其余部分。
答案 3 :(得分:0)
我看到你有两个选择。
选项1:
更改存储数据的方式(关键字在自己的表中,使用多对多关系将现有表与关键字表连接起来)。这将允许您使用DISTINCT。 DISTINCT目前不起作用,因为查询将“公司”和“公司,业务,战略”视为两个不同的值。
选项2:
写一些'有趣'的sql来分割关键字字符串。我不知道MySQL的限制是什么,但SQL通常不是为此而设计的。