【解決方法】同じステートメントで複数の mysql クエリからデータを取得し、フロントエンドで結果をレンダリングするにはどうすればよいですか?


同じデータベース内の 2 つの異なるテーブルのデータを表示するダッシュボードを作成しています。 1 つのクエリに対しては実行できますが、複数のクエリに対しては実行できません

私が試したこと:

const mysql = require('mysql');
const Q = require('q')


// Connection Pool
const pool = mysql.createPool({
    multipleStatements: true,
    connectionLimit : 100,
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE,
})

// View home-data
exports.view = (req, res) => {

    // Connect to database - box 1
pool.getConnection((err, connection) => {
    if(err) throw err; //Not Connected
    console.log('Connected as ID ' +  connection.threadId);

  

    connection.query('SELECT (SELECT COUNT(*)  FROM table1) AS totalRecords1, (SELECT COUNT(*)  FROM table2) AS totalRecords2', (err, rows1, rows2) => {

        // When finished with connection, release it
     connection.release()
        if(!err) {
           let res1 = JSON.parse(JSON.stringify(rows1[0]['totalRecords1']));
           let res2 = JSON.parse(JSON.stringify(rows2[0]['totalRecords2']))
            console.log(`row1: ${res1}, row2 ${res2}`)
           
            res.render('home', {
                rows1: res1,
                rows2: res2})
        }else {
            console.log(err)
            }
        })
    })
  };

解決策 1

オンラインMySqlサンドボックス(MySQL オンライン – SQL クエリのテスト[^]):

SQL
create table scientist1 (id integer, firstname varchar(100), lastname varchar(100));
insert into scientist1 (id, firstname, lastname) values (1, 'albert', 'einstein');
insert into scientist1 (id, firstname, lastname) values (2, 'isaac', 'newton');
insert into scientist1 (id, firstname, lastname) values (3, 'marie', 'curie');
create table scientist2 (id integer, firstname varchar(100), lastname varchar(100));
insert into scientist2 (id, firstname, lastname) values (1, 'albert', 'einstein');
insert into scientist2 (id, firstname, lastname) values (2, 'isaac', 'newton');
insert into scientist2 (id, firstname, lastname) values (3, 'marie', 'curie');
insert into scientist2 (id, firstname, lastname) values (4, 'marie', 'curie');
insert into scientist2 (id, firstname, lastname) values (5, 'marie', 'curie');
SELECT (SELECT COUNT(*)  FROM scientist1) AS totalRecords1, (SELECT COUNT(*)  FROM scientist2) AS totalRecords2

私が期待するものを手に入れます:

totalRecords1   totalRecords2
      3               5

だから…クエリは機能します。

DB と取得した実際の結果を確認することから始めます。ログ エントリを使用して、そこでエラー メッセージを確認します。

コメント

タイトルとURLをコピーしました