简体   繁体   中英

PHP Loop with Multiple Nested SQL Query

I have two tables and I wish to display all the contents but grouping together the contents by a certain field - the job_id field:

The two tables:

  • job_experience

job_id (Primary Key)
job_name
user_id

  • job_skills

skill_id (Primary Key)
job_id
skill_name

This should produce by matching both tables job_ids:

Job Name 1
Skill 1
Skill 2

Job Name 2
Skill 1

I currently have the working loop for the Experience table, but I'm unable to determine how to also include the job_skills and group it together via job_id. I attempted a nested loop with a SQL query focused on matching the job_ids, but this did not work.

<?php

$experience_sql =mysql_query("select e.job_id, e.job_name,from   job_experience e where e.user_id='$user_id_session'", $connection);


while ($row = mysql_fetch_assoc($experience_sql)) {
    ?>
<textarea cols="50" rows="10">
<?php
    echo $row['job_name']." "."\n";

    ?>
    </textarea>
    <?php
}
?>

May be you are looking for the statement like this

select e.job_id, e.job_name,s.skill_name from   job_experience e, job_skills s where e.job_id=s.job_id and e.user_id='$user_id_session'

or

select e.job_id, e.job_name,s.skill_name from   job_experience e inner join job_skills s on e.job_id=s.job_id where e.user_id='$user_id_session'

You can use the following query to get all skills in relation to jobs as a comma separated list:

SELECT e.job_id, e.job_name, GROUP_CONCAT(s.job_skills)
FROM job_experience e
LEFT JOIN job_skills s ON e.job_id = s.job_id
GROUP BY e.job_id
<?php 
$experience_sql = mysql_query("select e.job_id, e.job_name, s.skill_name from job_experience e inner join job_skills s on e.job_id=s.job_id where e.user_id='$user_id_session' ",$connection);

while ($row = mysql_fetch_assoc($experience_sql)){
   ?>
 <textarea cols="50" rows="10">
<?php
echo $row['job_name']." "."\n";
 echo $row['skill_name']." "."\n";

?>
</textarea>
<?php
}
?>

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