简体   繁体   中英

How can i run two queries on three tables and output the result of a column in one table

I tried coming up with a better title, and I wish there was a chat that I could join to better discuss what i mean. Anyway, I have a while loop running that pulls data from two tables and displays the results correctly. I have a third table that I want to display the name of a result based on what id comes out in a loop... See what i mean, it doesn't make sense.

Here is the queries and loop:

                try {
                $stmt = $Conn->prepare("SELECT * FROM wn_trailer "
                        . "INNER JOIN wn_trailer_history ON wn_trailer.id = wn_trailer_history.trailer_id "
                        . "ORDER BY trailer_number ASC");
                $stmt->execute();

                $stmt2 = $Conn->prepare("SELECT status_name FROM wn_trailer_status WHERE status_id = :status");
                $stmt2->execute([":status" => $row[1]]);

                while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {

                    $data = "<tr>\r\n<td><a href='view-trailer.php?id=$row[0]'>" . $row[1] . "</a></td>\r\n"
                            . "<td>" . $row[1] . "</td>\r\n"
                            . "<td>" . $row[16] . "</td>\r\n"
                            . "<td><a href='https://www.google.com/maps/search/?api=1&query=$row[3],$row[4]' target='_blank'>View Map</a></td>\r\n"
                            . "</tr>\r\n";
                    print $data;
                }
            } catch (PDOException $e) {
                print $e->getMessage();
            }

$stmt2 is the second query that is hitting the third table. As the loop runs i want it to compare a result from the first query, and if it finds the id to return the value in the column. The query is good, i checked it in the mysql log, but it is not returning a value.

Another option i was thinking about doing is writing a function that runs through the wn_trailer_status and creates a select case, and using that to compare the results that why i'm not banging against the database a bunch of times.

tldr; My question is how can i compare the results from the first query against the second query and display the result of a column, or should i use a select case function to handle the work load?

assuming the value status is retun by the first query form table wn_trailer you could resolve both the query using adding an inner join

 $stmt = $Conn->prepare("SELECT * 
             FROM wn_trailer  
             INNER JOIN wn_trailer_history ON wn_trailer.id = wn_trailer_history.trailer_id 
             INNER JOIN wn_trailer_status  ON wn_trailer_status.status_id = wn_trailer.status
             ORDER BY trailer_number ASC");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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