Mushood Hanif
Mushood Hanif

Reputation: 751

Cannot Get Data From Nested SQL Query

const getCompanyShifts = (req, res) => {
  try {
    const { company_id } = req.params;
    connection.query(
      `SELECT * FROM jobs WHERE company_fk=${company_id}`,
      (err, rowss) => {
        if (!err) {
          connection.query(
            `SELECT * FROM shift WHERE isBooked=1 AND fk_job = ?`,
            [rowss.jobsID],
            (err, rows) => {
              if (err || rows.length === 0) {
                res.status(404).json({
                  success: false,
                  message: "Company Shifts Not Found!",
                  err,
                });
              } else {
                const shifts = [];
                rows.forEach((row, i) => {
                  const shift = {
                    shiftID: rows[i].shiftID,
                    shiftStartTime: rows[i].startTime,
                    shiftEndTime: rows[i].endTime,
                    shiftDate: rows[i].date,
                    isBooked: rows[i].isBooked,
                    fk_job: rows[i].fk_job,
                    fk_guard: rows[i].fk_guard,
                  };
                  shifts.push(shift);
                });
                res.status(200).json({
                  success: true,
                  message: "Successfully Retrieved Company Shifts!",
                  shifts,
                });
              }
            }
          );
        } else {
          res.status(404).json({
            success: false,
            message: "Company Jobs Not Found!",
          });
        }
      }
    );
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message,
    });
  }
};

in the first query of the above code, i am getting all the rows from the jobs table. In the second nested query, i am trying to get all rows from the shift table for each of the jobsID returned from the 1st query. But i don't get any data back. The data exists and it should return data but i don't get any data back. What am i doing wrong here ? Please help!

Upvotes: 0

Views: 50

Answers (1)

mottek
mottek

Reputation: 957

i assume there is a misunderstanding on how the data gets returned and therefore how the second query would work. According to your statement:

[...] i am getting all the rows from the jobs table. In the second nested query, i am trying to get all rows from the shift table for each of the jobsID returned from the 1st query. But i don't get any data back.

You are getting multiple rows back. So the first query works. But getting multiple rows back would result in rowss being an array. Therefore rowss.jobsID which is used as input for the next query isn't a correct use of an array and i expect the value of that expression to be undefined which will then result in the second query not returning anything.

To prove that add console.log(rowss) like so:

[...]
connection.query(
  `SELECT * FROM jobs WHERE company_fk=${company_id}`,
  (err, rowss) => {
    console.log(rowss);
[...]

To solve the issue, i suggest to use sql capabilities and issue a join. By doing so, the Database will join the two tables, then returning only rows that fulfill the where condition. The combined statement should look like:

SELECT * FROM jobs WHERE company_fk=${company_id} LEFT JOIN shift ON shift.fk_job = jobs.jobsID WHERE isBooked=1

Hint: Depending on your DB schemes for ob'sand shift you might need to expand the * and list all table names explicitly, e.g. SELECT jobs.jobsID, jobs.<xyz>, shift.isBooked, shift.fk_job [...] FROM [...]. If you have column with same name in both tables, you might need to resolve the conflict which is caused by the join while combining the columns for returning the results like so: SELECT [...] shift.<xyz> as shift_xyz [...] FROM ...[].

As a plus, you also just need one SQL query instead of two.

Upvotes: 1

Related Questions