Nodejs在sql中选择Subselect

时间:2018-01-16 13:21:11

标签: javascript mysql node.js sequelize.js

奥拉!

我正在做一个node.js应用程序。我的MySql DB中有这个表结构:

enter image description here

我的任务是获取 table_4名称和相关的 table_7名称。我知道Table_1的用户名和密码。是否可以创建一个查询 - 使用subselect - 获取值后不用新选择调用所有时间回调? - 如下 -

con.connect(function(err) {  
    if (err) 
    {throw err }  
    con.query("SELECT id FROM Table_1 WHERE username = xyz AND password = aaa", 
        function (err, result) {
           if (err) {throw err};
           con.query("SELECT table_3_id FROM table2 WHERE Table_1_id = "+(result)+")", 
                  function(/*bla-bla*/){

                  };   
                }); 
    }
);

谢谢!

2 个答案:

答案 0 :(得分:1)

这是通过一个查询实现这一目标的方法:

SELECT  Table_4.*
FROM    Table_1 , Table_2 , Table_3 , Table_4
WHERE   Table_1.username and Table_1.password and 
        Table_2.Table_1_id = Table_1.id and 
        Table_2.Table_3_id = Table_3.id and
        Table_3.Table_4_id = Table_4.id

我找不到Table_7名称的正确关系。但我想你会明白如何从中做到这一点。

答案 1 :(得分:0)

我刚跟我的主要开发人员谈过,他给了我一个正确的解决方案 - 类似于@Vivek Doshi回答 - :

SELECT  Table_4.names, Table_7.names
FROM    Table_1 , Table_2 , Table_3 , Table_4, Table_5, Table_6, Table_7
WHERE   Table_1.username and Table_1.password and 
        Table_2.Table_1_id = Table_1.id and 
        Table_2.Table_3_id = Table_3.id and
        Table_3.Table_4_id = table_4.id and
        Table_3.table_5_id = table_5.id and
        table_6.table_5_id = Table_5.id and
        table_6.table_7_id = table_7.id;