繁体   English   中英

MySQL使用table1.id REGEXP table2.id为同一组选择不同的行

[英]MySQL select distinct rows for same group using table1.id REGEXP table2.id

表名:组

id  name
1   ONE
2   TWO
3   THREE
4   FOUR
5   FIVE
6   SIX

表格名称:标题

id  title           groups  isactive
1   First Title     1,2,4   yes
2   Second Title    2,5,7   yes
3   Third Title     3,1,2   yes
4   Fourth title    2,4,5   yes

链接列:ID

查询:

SELECT 
 t.*, g.name
FROM 
 `titles` AS t, groups AS g 
WHERE 
  t.groups REGEXP CONCAT('^', g.id, '')
ORDER by title ASC, name ASC

结果:

id  title           groups  isactive    name
1   First Title     1,2,4   yes         ONE
4   Fourth title    2,4,5   yes         TWO
2   Second Title    2,5,7   yes         TWO
3   Third Title     3,1,2   yes         THREE

现在,问题是我只希望为每个组选择一个标题,但是,可能会有重复的组名,如(id = 4和2)都分配给组号TWO。

仅显示高ID的人? 然后结果应该是这样的:(不包括id = 2)

id  title           groups  isactive    name
1   First Title     1,2,4   yes         ONE
4   Fourth title    2,4,5   yes         TWO
3   Third Title     3,1,2   yes         THREE

我也尝试使用此查询:

SELECT 
 t.*, g.name
FROM 
 `titles` AS t, groups AS g 
WHERE 
  t.groups REGEXP CONCAT('^', g.id, '')
GROUP by g.name
ORDER by t.id DESC 

要么

ORDER by t.id ASC

但两者都显示:

id  title           groups  isactive   name
3   Third Title     3,1,2   yes        THREE
2   Second Title    2,5,7   yes        TWO
1   First Title     1,2,4   yes        ONE

请查看演示-SQL FIDDLE

尝试这个

SELECT A.*, B.NAME FROM titles A
JOIN (
         SELECT g.name, max(t.id) id
         FROM titles AS t, groups AS g 
         WHERE t.groups REGEXP CONCAT('^', g.id, '')
         group by g.name
     ) B on A.id = b.id

SQL演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM