简体   繁体   中英

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

Table name: groups

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

Table name: titles

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

Link column: id

QUERY:

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

Results:

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

Now, the problem is I want to select only one title for each group, however, there might be duplicate group names like (id = 4 and 2) both assigned to group number TWO.

HOW TO ONLY SHOW THE ONE WITH HIGH ID? Then the result should be like this: (excluding 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

I tried using this query also:

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 

or

ORDER by t.id ASC

But both showing:

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

PLEASE SEE DEMO - SQL FIDDLE

Try this

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 DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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