PHP MySQL Selecting Multiple Tables Based on Column/Row Value

Aaron Esteban

I am just doing some testing with a few tables that I'm trying to relate together, based on the values of my 'students' table.

Here are the total tables that I have:

students TABLE

id, name, course_num, msg_num


biology TABLE

id, details, msg_num

chemistry TABLE

id, details, msg_num

physics TABLE

id, details, msg_num


So I'm trying to select the 'students' table first, and based on the 'course_num' & 'msg_num' values in the 'students' table, it will determine which table is selected out of an array of tables that I have (as shown above, the 'biology', 'chemistry', & 'physics' tables).

The 'students' table looks like this: enter image description here

The 'biology' table has data like this: enter image description here

The 'chemistry' table looks like this: enter image description here

The 'physics' table looks like this: enter image description here

So, once again, I'm trying to have it to where if the number in 'course_num' in the 'students' table is set to either '0,1,2' , then it will dynamically select the related table from the array list that I have set up in advance. Here is the exact code that I've tried below, but it is NOT syncing up properly. Please let me know what I'm doing wrong here:

<div style="position:relative; margin:auto; width:400px; font-family:Poppins; font-size:16px; border:2px solid black; padding:10px; margin-top:100px;">


<?php

include 'db_connect.php';


$selected_courses = array("biology", "chemistry", "physics");



$sql1 = "SELECT * FROM students";
$result1 = $conn->query($sql1);

while($row1 = $result1->fetch_assoc()){
    $course = $selected_courses[$row1['course_num']];

    $sql2 = "SELECT students.*, $course.*, FROM students, $course
    WHERE students.msg_num = $course.msg_num";

    $result2 = $conn->query($sql2);
    $row2 = $result2->fetch_assoc();

    echo "STUDENT NAME: ". $row2['name'] . "<br>";
    echo "DETAILS: ". $row2['details'] . "<br>";
    echo "MSG NUM: ". $row2['msg_num'] . "<br>";
    echo "<br>";
}


$conn->close();

?>

</div>
Tangentially Perpendicular

Your schema is basically wrong, and your code includes a nested query which is almost always the wrong way to do things.

Instead of three identical tables with different course data, set up one table and add a course_num column. This allows you to JOIN your students directly to their details rows, and you can use a single SELECT with a JOIN to extract the data.

So using your student table and this courseDetails table:

CREATE TABLE `courseDetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `msg_num` int NOT NULL,
  `course_num` int NOT NULL,
  `details` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;

You can JOIN on the common columns between the two tables like this:

select name, details, s.msg_num 
  from students s 
  join courseDetails d 
    on (s.course_num = d.course_num AND s.msg_num = d.msg_num);

To get this output in a single query:

name details msg_num
Adam Smith Biology Details #0 0
John Wright Chemistry Details #1 1

From that you can vary the JOIN conditions and use WHERE clauses to create different output as you need, all from the two basic tables.

This simplifies your PHP code to


include 'db_connect.php';

$sql1 = "select name, details, s.msg_num from students s join courseDetails d on (s.course_num = d.course_num AND s.msg_num = d.msg_num);";

$result1 = $conn->query($sql1);

while($row1 = $result1->fetch_assoc()){
    echo "STUDENT NAME: ". $row1['name'] . "<br>";
    echo "DETAILS: ". $row1['details'] . "<br>";
    echo "MSG NUM: ". $row1['msg_num'] . "<br>";
    echo "<br>";
}

$conn->close();

?>

Demo:https://www.db-fiddle.com/f/3cmTkGhEgiBEUZS7dFNvnz/0

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

I need assistance with my MySql query (selecting from multiple tables)

Selecting from multiple tables in laravel

selecting N particular tables from MySQL

Joining multiple tables in MySQL

Querying multiple tables on MySQL

How to query multiple tables in mysql

selecting value in one row of DataFrame based on value in other

Как вставить опцию множественного выбора в PHP MySQL, когда включен multiple = 'multiple'

Mysql problem Select multiple tables problem in mysql

Selecting rows from a Dataframe based on values from multiple columns in pandas

Selecting columns based on value given in other column using pandas in python

Selecting 1 record based on last unique value that is on another column

JOIN Tables based on the column value in oracle

JOIN Tables based on the column value in oracle

Finding value based on multiple criteria

Mysql one middle table for multiple similar tables

Joining Multiple MySQL tables with Same Column Name

How to UPDATE multiple tables with 1 query in MYSQL

MYSQL Combing Two tables From Multiple Row

Join 2 Tables with 2 conditions (MySQL and PHP)

Comparing MySQL rows from different tables in PHP

TSQL Compare tables based on multiple rows same column?

sql update table column based on values across multiple tables

MYSQL Distict value from many tables with smallerst value

Sql - loop through two tables and sum a value based on condition

PHP JSON multiple echo value

Описание сценария PHP Multiple Mysql Insert. Как?

PHP/MySQL multiple nested SELECTs

Laravel multiple query (PHP/MySQL)

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  3. 3

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  4. 4

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  5. 5

    How to click an array of links in puppeteer?

  6. 6

    Merging legends in plotly subplot

  7. 7

    ViewPager2 мигает / перезагружается при смахивании

  8. 8

    Отчеты Fabric Debug Craslytic: регистрация, отсутствует идентификатор сборки, применить плагин: io.fabric

  9. 9

    How to normalize different curves drawn with geom = "step" when using stat_summary

  10. 10

    无法通过Vue在传单中加载pixiOverlay

  11. 11

    как я могу удалить vue cli 2?

  12. 12

    Как я могу нарисовать заполненный прямоугольник в JFreeChart?

  13. 13

    SQL Вычтите две строки друг от друга в одном столбце, чтобы получить результат

  14. 14

    Elasticsearch - Нечеткий поиск не дает предложения

  15. 15

    Single legend for Plotly subplot for line plots created from two data frames in R

  16. 16

    Описание моего типа Parser как серии преобразователей монад

  17. 17

    Как изменить цвета запятых и скобок в VS Code

  18. 18

    Сброс значения <input type = "time"> в Firefox

  19. 19

    Почему прокси в vue.config.js 404

  20. 20

    Как установить параметр -noverify с gradle ktx для робоэлектрических тестов Android?

  21. 21

    В чем разница между ifstream, ofstream и fstream?

популярныйтег

файл