【问题标题】:Database Inter Relation between rows行之间的数据库相互关系
【发布时间】:2015-09-02 10:35:04
【问题描述】:

有一个文章表,其中包含“article_id、title、year_published”字段。表中数据:

------------------------------------
article_id | title | year_published
------------------------------------ 
1|Mechanical Code|2012 
2|Mechanical Code|2015 
3|Contruction Workshop|2010 
4|Contruction Workshop|2012 
5|Contruction Workshop|2013 
6|Administrative Session I|2012 
7|Administrative Session II|2014 
8|Administrative Session III|2015

我需要找出存在多年的同一篇文章。

我已查询我的数据库以获取按标题分组且计数超过 1 的结果。

从文章组中选择标题,计数(*)作为总数 总计 > 1;

但问题是标题名称可能不同,并且同一篇文章有​​不同的版本。看第 6-8 行及以上查询不会得到管理会话。

如何处理这种关系?

【问题讨论】:

  • 您需要修改名称。 SQL 查询无法为您执行此操作,除非您可以指定所需的规则。
  • @GordonLinoff :我无法更改标题。我可以创建一个新表。那这种情况怎么处理呢?
  • @AnkiiGangrade : 是否存在指定article_id 6,7, & 8 属于同一文章组或共享共同属性的表?
  • @seahawk 不,它不存在。新表可以做到这一点。管理员将选择它们已链接。
  • @AnkiiGangrade : 有没有固定的格式添加版本..?

标签: mysql database database-design


【解决方案1】:

例如,您可以添加另一个整数类型的字段“articletype”,并将Administration Session I、Administrative Session II和Administrative Session III设置为相同的文章类型。

--------------------------------------------------
article_id | title | year_published| articletype
--------------------------------------------------
1|Mechanical Code|2012|1
2|Mechanical Code|2015|1
3|Contruction Workshop|2010|2
4|Contruction Workshop|2012|2
5|Contruction Workshop|2013|2
6|Administrative Session I|2012|3
7|Administrative Session II|2014|3
8|Administrative Session III|2015|3

SQL 应该是这样的:

select title, count(*) as total from articles group by articletype  having total > 1;

【讨论】:

  • 我使用了相同的方法,但方式略有不同。谢谢
【解决方案2】:

如果你知道它是一个数字,你可以删除标题的最后部分。像这样的:

select (case when substring_index(title, ' ', -1) in ('I', 'II', 'III')
            then left(title, length(title) - locate(' ', reverse(title)))
            else title
       end) as basetitle, count(*) as total
from articles
group basetitle
having count(*) > 1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 2021-06-13
    • 2021-04-07
    • 1970-01-01
    相关资源
    最近更新 更多