2011-02-13 216 views
0

我有一個課程頁面,此頁面設置爲顯示詳細信息(簡單),然後誰在教授每個學期的第一,第二,第三和第四個週期。問題在於,我的教師數據是在一個巨大的鏈條中處理的。MySQL查詢搜索(高級)

鮑比:1-1-1-1-1-1-1-1

蒂娜:20-20-20-10-1-1-1-1

喬伊:20- 1-1-1-49-432-10-19

我想要做的是找到一個課程:20,當顯示所有信息時,通過教師搜索將找出誰在教授課程20和什麼時期?

Ex。

Course id: 20 
Period 1: Joey, Tina 
Period 2: Tina 
Period 3: Tina 

我想每一位教師在教學一個搜索該課程,但鑑於這可能是一個問題capact數據的障礙。

教師表: ID /名稱/鏈接/場(1-1-1-1-1-1-1-1)

課程表: ID /名稱/代碼/級/水平

教師課程包含的ID從課程表

+0

什麼是你的數據庫看起來像通緝名單? (dbms,結構,版本) – GolezTrol 2011-02-13 14:06:30

+4

這是誰存儲它? – 2011-02-13 14:07:31

回答

1

在重新構建你的數據庫可能是最好的答案,我想我會發佈一個直PHP的解決方案,與當前的結構工程和推定休息的代碼。

//I set up variables to contain your expected search results so I could test 
$search_course = '20'; 
$search_results = array(
    'Bobby' => '1-1-1-1-1-1-1-1', 
    'Tina' => '20-20-20-10-1-1-1-1', 
    'Joey' => '20-1-1-1-49-432-10-19' 
    ); 

//explode the course strings into arrays and store with teacher names so 
//you can loop through them later 
foreach($search_results as $teacher=>$string_courses){ 
    $array_courses = explode('-',$string_courses); 
    $search_results[$teacher] = $array_courses; 
    } 

//Match course you are searching for to the elements in your array 
//Create a result array with period and matching teachers 
foreach($search_results as $teacher=>$courses){ 
foreach($courses as $period => $course){ 
    if($course == $search_course){ 
      $results[$period][] = $teacher; 
      } 
     } 
    } 

//Loop through your result array and show the results 
//I expect you'll have different html for this 
foreach($results as $period => $teachers){ 
    echo 'Period: '; 
    echo $period+1; 
    echo implode(',',$teachers); 
    echo '<br>'; 
} 

打印結果符合您在您的OP

0

你應該改變,而不是存儲所有時期的字符串你的數據庫的結構,你應該有三列附加表:老師,當然,週期和在這個表格中爲每個老師教授的課程單獨一行。然後,確定誰在教授什麼課程只是按課程ID查詢該表格,然後按期間排序。 e.g:

SELECT teacher_id, course_id, period FROM course_info WHERE course_id = 20 
ORDER BY period; 
1

創建新表

事情是這樣的:

CREATE TABLE `TeacherToPeriod` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , 
`TeacherID` INT NOT NULL , 
`CourseID` INT NOT NULL , 
`Period` INT NOT NULL 
) ENGINE = MYISAM ; 

插入數據

這裏是一些PHP-代碼:

foreach($lines as $line){ 
    $line_data = split($line, ': '); 
    $teacher = $line_data[0]; 
    // SELECT your $teacher_id from the database 

    $courses = split($line_data[0], '-'); 
    $i = 0; 
    foreach($courses as $course_id){ 
     $i++; 
     $sql = "INSERT INTO `TeacherToPeriod` (`TeacherID` ,`CourseID` ,`Period`) "; 
     $sql.= "VALUES ($teacher_id, $course_id, $i);" 
     mysql_query($sql); 
    } 
} 

選擇數據你想

SELECT * FROM `TeacherToPeriod` WHERE `CourseID` = 20 ORDER BY `Period` ASC;