【问题标题】:What is the right way ? With javascript and mysql什么是正确的方法?使用 javascript 和 mysql
【发布时间】:2023-03-15 16:30:01
【问题描述】:

我有一个名为“汽车”的 mysql 表,我在其中存储:“品牌”、“型号”、“颜色”。我想得到这样的数据:

[
    {
        brand: "audi",
        cars: [
            {
                "model": "coupe",
                "color": "red",
            },
            {
                "model": "a3",
                "color": "blue",
            },
        ]
    },
    {
        brand: "renault",
        cars: [
            {
                "model": "modus",
                "color": "white",
            },
            {
                "model": "clio",
                "color": "green",
            },
        ]
    },
    ...
]

所以,我正在做的是第一个 mysql 查询,我按品牌分组,然后我迭代结果以获取每个品牌的所有汽车:

const query = "SELECT brand FROM cars GROUP BY brand"
mysql.query(query, values, (err, result) => {
    for (let i = 0; i < result.length; i++) {
        const query2 = "SELECT model, color FROM cars WHERE brand = ?"
        const values2 = [result[i].brand]
        mysql.query(query2, values2, (err2, result2) => {
            result[i].cars = result2
            callback(result)
        })
    }
})

我展示的代码正在运行,但我不认为对 mysql 查询进行迭代是一件好事。

我做了很多研究,但我真的不知道该怎么做。

是否有可能通过一个 mysql 查询得到这个结果?或者我应该从“汽车”表中获取所有行,然后做 JS 的东西来格式化数据?还是我应该继续使用这个 mysql 查询迭代?

谢谢

【问题讨论】:

  • 如果您不想转换数据,为什么不使用像 MongoDB 这样的面向 json 的数据库?
  • 问题是你想返回原始数据给客户端还是分组数据。最好的做法并不重要,重要的是需要数据的人如何处理数据。
  • @MauriceNino 我不能用 MongoDB .. 我已经用 mysql 运行了一个 web 应用程序,我没有抱怨这个
  • @briosheje 数据是客户端需要的,所以我可以在服务器或客户端进行转换
  • 您可以使用 :` "SELECT model, color FROM cars WHERE brand IN ('renault','bmw')"` 并在 JS 中对整体进行分组

标签: javascript mysql arrays object


【解决方案1】:

这样的事情应该可以解决问题。但它的客户端转换:

let carArr = []

const query = "SELECT brand, model, color from cars"
mysql.query(query, values, (err, result) => {
    for (let i = 0; i < result.length; i++) {
        // Get the index of the brand in the carArr array
        let brandIndex = carArr.map(c => c.brand).indexOf(result.brand)

        // If the brand is not already in carArr, enter a new value for it
        if(brandIndex == -1)
            carArr.push({"brand": result.brand, "cars": [{"model": result.model, "color": result.color}]})

        // If the brand already exists, add the car type to this specific barnd
        else
            carArr[brandIndex].cars.push({"model": result.model, "color": result.color})
    }
})

【讨论】:

  • 没问题!如果它对您有帮助,请随时接受答案。感谢您让我意识到我的问题(我实际上对此进行了盲编码)!更新了我的答案。
【解决方案2】:

你可以这样做:

const carsByBrand=[],brands={};  
function find(){
 const query = "SELECT model, color FROM cars WHERE brand IN ('renault','bmw')"
 mysql.query(query, values, (err, result) => {
    /*assuming value  to be like: [
            {
              brand:audi,
                "model": "coupe",
                "color": "red",
            },
            ]
       */

  values.forEach((car)=>{
      if(brands[car.brand]){
        carsByBrand[brands[car.brand]].cars.push(car)
      }else{
        let index=carsByBrand.push({
          brand:car.brand,
          cars:[car]
        })
        brands[car.brand]=index;
      }
    })    
  }
 })

}
find()

【讨论】:

  • 我没试过,其他答案很好。但是感谢您的快速答复!
【解决方案3】:

我们可以通过使用GROUP_CONCAT,CONCAT mysql函数来实现单个查询。 一旦你得到结果汽车密钥将 JSON 字符串。您可以使用 JSON.parse 方法进行转换

select brand,CONCAT("[",GROUP_CONCAT(CONCAT("{'model':'",model,"','color':'",color,"'}")),"]") as cars from cars GROUP BY brand;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 2019-05-17
    • 2014-12-08
    • 1970-01-01
    • 2011-11-11
    • 2015-03-01
    相关资源
    最近更新 更多