简体   繁体   English

计算 MySQL JSON 表中数组内项目的第一次出现

[英]Count the first occurence of items inside arrays in MySQL JSON table

I have a MySQL table where all the company sales for a given period are grouped by unit, date and, inside an array, all the sales representatives IDs that were involved in each sale.我有一个 MySQL 表,其中给定期间的所有公司销售额都按单位、日期分组,并且在一个数组中,包含每次销售中涉及的所有销售代表 ID。 The first sales_rep ID in each array shows which sales representative was responsible for closing each sale.每个数组中的第一个 sales_rep ID 显示负责完成每次销售的销售代表。 I am trying to elaborate a query that returns the unit, the date and the sales_rep ID for each sales representative that closed each sale.我正在尝试详细说明一个查询,该查询为关闭每笔销售的每个销售代表返回单位、日期和 sales_rep ID。 It is ok if a sales_rep ID is shown more than once for given date.如果在给定日期多次显示 sales_rep ID,则可以。

What I have as input:我有什么作为输入:

unit_id   date   unit_sales   sales_reps
427     2019-07-01   3     [["19823508","19823510",""],["23661230","23661227","23411261",""],["23411257","19823508",""]]
466     2019-07-26   2     [["23222763","23222766","26726848","26726849",""],["23222763",""]]

The desired output is:所需的输出是:

unit_id   date      sales_rep
427     2019-07-01  19823508
427     2019-07-01  23661230
427     2019-07-01  23411257
466     2019-07-26  23222763
466     2019-07-26  23222763

This is too long for a comment.评论太长了。

You should really consider fixing your data model.真的应该考虑修复您的数据模型。 Storing structured data (csv, arrays, etc) in a text column will bite you in many ways.将结构化数据(csv、数组等)存储在文本列中会在很多方面困扰您。 Typically, what you want to do here will necessarily involve a SQL with lot of complexity.通常,您要在这里执行的操作必然涉及具有很多复杂性的 SQL。 This can be avoided by adopting a data model that better fits to your use case, for example:这可以通过采用更适合您的用例的数据模型来避免,例如:

  • create a separate table to store the list of sales reps that were involved in each unit sale, with a boolean column that indicates which sales rep closed the sale;创建一个单独的表来存储参与每个单位销售的销售代表列表,并带有一个布尔列,指示哪个销售代表完成了销售; this seems like the right way to do it这似乎是正确的方法

  • or, as an intermediate solution, transform your text column to a json column: this is less clean, but at least you could take advantage of json functions when accessing your data或者,作为中间解决方案,将您的文本列转换为 json 列:这不太干净,但至少您可以在访问数据时利用 json 函数

Related reading: Is storing a delimited list in a database column really that bad?相关阅读: 在数据库列中存储分隔列表真的那么糟糕吗?

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

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