简体   繁体   English

父查询中每行的子查询-Node.js和Node-mssql

[英]Child query for each row in Parent query - Node.js and node-mssql

I am trying to figure out the most efficient way to do the following using Node.JS and node-mssql. 我试图找出最有效的方法来使用Node.JS和node-mssql执行以下操作。 I want an end result that looks like this: 我想要一个看起来像这样的最终结果:

{
   movie_id: '1234',
   name: 'Hereditary',
   countries: [
      "Canada",
      "United States",
      "Australia"
  ]
},
{
   movie_id: '1235',
   name: 'Rosemarys Baby',
   countries: [
      "Canada"
  ]
}

My tables look like this 我的桌子看起来像这样

movies: 电影:

movie_id    | name 
---------------------
1234        | Hereditary
1235        | Rosemarys Baby

movie_countries: movie_countries:

id  |  movie_id    | country
---------------------
1   |  1234        | Canada
2   |  1234        | United States
3   |  1234        | Australia
4   |  1235        | Canada

So far, I've tried several of the different examples from mssql's Github page. 到目前为止,我已经尝试了mssql的Github页面中的几个不同示例。 I am able to get the results from the "movies" table, but I'm getting stuck when trying to get the countries for each movie. 我可以从“电影”表中获得结果,但是在尝试获取每部电影的国家/地区时我陷入困境。

Fetch all the data of movies table and movie_countries table in respective variables. 在相应的变量中获取movies表和movie_countries表的所有数据。

movies.forEach(function(movie) {
    movie.countries = _.remove(movie_countries, function(mc) {
        return movie.movie_id === mc.movie_id; //Edited this from = to ===
    });
});

Sql Way: SELECT mv.movie_id, mv.name, GROUP_CONCAT(mvc.country) AS countries FROM movies mv LEFT JOIN movie_countries mvc ON mv.movie_id = mvc.movie_id WHERE 1 GROUP BY mv.movie_id SQL方式:从电影mv左联接movie_countries mvc上选择mv.movi​​e_id,mv.name,GROUP_CONCAT(mvc.country)AS国家mv.movi​​e_id = mvc.movi​​e_id WHERE 1 GROUP BY mv.movi​​e_id

movies.forEach(function(movie) {
    movie.countries = movies.countries.length ? movies.countries.split(',') :[];
});

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

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