简体   繁体   English

node.js使用两个表获取mysql数据

[英]node.js fetch mysql data using two tables

Table lists 表格清单

id | id | user_id | user_id | name 名称

1 | 1 | 3 | 3 | ListA 利斯塔
2 | 2 | 3 | 3 | ListB 数组listB

Table celebrities 餐桌名人

id | id | user_id | user_id | list_id | list_id | celebrity_code celebrity_code

1 | 1 | 3 | 3 | 1 | 1 | AA000297 AA000297
2 | 2 | 3 | 3 | 1 | 1 | AA000068 AA000068
3 | 3 | 3 | 3 | 2 | 2 | AA000214 AA000214
4 | 4 | 3 | 3 | 2 | 2 | AA000348 AA000348

I am looking a JSON object like this 我正在寻找这样的JSON对象

[ {id:1, name:'ListA', celebrities:[{celebrity_code:AA000297},{celebrity_code:AA000068}]}, [{id:1,名称:“ ListA”,名人:[{celebrity_code:AA000297},{celebrity_code:AA000068}]},

{id:2, name:'ListB', celebrities:[{celebrity_code:AA000214},{celebrity_code:AA000348}]} {id:2,名称:“ ListB”,名人:[{celebrity_code:AA000214},{celebrity_code:AA000348}]}
] ]

Moved this to an answer since the details were getting long, and I thought the additional references would be useful to future readers. 由于细节变得冗长,因此将其移到了答案上,我认为其他参考资料将对将来的读者有用。

Since you are using MySQL, check out GROUP_CONCAT . 由于您使用的是MySQL,因此请签出GROUP_CONCAT To get your object, you will want to GROUP_CONCAT on a CONCAT enated string. 要获取您的对象,您需要对CONCAT枚举的字符串使用GROUP_CONCAT If you could live with a schema more like {id:2, name:'ListB', celebrity_codes:['AA000214','AA000348']} you'll have a simpler query. 如果您可以使用更像{id:2, name:'ListB', celebrity_codes:['AA000214','AA000348']}查询{id:2, name:'ListB', celebrity_codes:['AA000214','AA000348']}简单。 If you make a SQLfiddle of your basic schema (basically your create tables plus the inserts of the above sample data), someone might even write it for you. 如果您使用基本架构的SQLfiddle (基本上是您的创建表以及上述示例数据的插入),那么有人甚至可以为您编写它。 :-) :-)

To be clear, while GROUP_CONCAT can do this, if you are trying to generate more than a fairly simple schema, it gets to be some pretty messy code and it starts making more and more sense to move it into your application layer both from a code maintenance standpoint as well as performance & scalability considerations. 需要明确的是,尽管GROUP_CONCAT可以做到这一点,但是,如果您尝试生成的不仅仅是一个简单的模式,它将变得有些混乱,并且将代码从代码中移动到应用程序层变得越来越有意义维护观点以及性能和可伸缩性方面的考虑。

Also note that SQLLite supports GROUP_CONCAT , for other databases: 还要注意,SQLLite支持其他数据库的GROUP_CONCAT

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

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