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

标签 php mysql sql regex

表名:组

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

请参阅 DEMO - 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 DEMO

关于php - MySQL 使用 table1.id REGEXP table2.id 为同一组选择不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14781918/

相关文章:

php - 从 PHP 页面运行 Shell 脚本

php - session 安全?

mysql - 需要显示来自 2 个单独表的匹配记录

php - Symfony Doctrine 查询错误

php - Google checkout,如何清除我的购物车?

php - 测试/调试/修复 PHP 并发问题的工具?

php - 根据最后插入的 id 生成唯一标识符

php - mysql插入查询变量问题

sql - 甲骨文朱利安一天

sql - 如何删除没有主键的重复行