2013-11-25 78 views
2

我建立2次的查詢的$project_id變量進行比較,以下面的流程圖中所示MEETING & MEETING_AGENDA 2個表:需要幫助建立一個MySQL查詢一個可變比較兩個表

        +---------------------+ 
       +------------+  | MEETING_AGENDA | 
       | MEETING |  +---------------------+ 
       +------------+  | meeting_agenda_id | 
       | meeting_id |----->| meeting_id   | 
$project_id --->| project_id |  | meeting_agenda_name | 
       +------------+  +---------------------+ 

這背後的邏輯流程圖是,我已經存儲了一個名爲$project_id的變量作爲輸入。如果$project_id = MEETING.project_id那麼我需要存儲一個MEETING.meeting_id的列表。 MEETING中有多個project_id的重複項,導致產生了一組meeting_id(僅供說明)。如果有任何的MEETING.meeting_id= MEETING_AGENDA.meeting_id然後打印meeting_agenda_name

我凌亂的嘗試(工作)看起來是這樣的:

$project_id = $_SESSION['PROJECT_ID']; 
$query1 = 
" 
SELECT meeting_id, meeting_project_id 
FROM MEETING 
WHERE project_id = $project_id 
"; 

$result1 = mysqli_query($con, $query1) or die("Query error: " . mysqli_error($con)); 

while($row = mysqli_fetch_array($result1)){ 
    $meeting_ids = $row['meeting_id']; 

    $query2 = 
    " 
    SELECT * 
    FROM MEEITNG_AGENDA 
    WHERE meeting_id = $meeting_ids 
    "; 

    $result2 = mysqli_query($con, $query2) or die("Query error: " . mysqli_error($con)); 

    while($row2 = mysqli_fetch_array($result2)){ 
    echo $row2['meeting_agenda_name'] . "<br>" 
    } 
} 

我用2查詢的,我想如果可能的話擦拭本成1個查詢。我曾嘗試在單個查詢中進行各種嘗試,但沒有任何解決方案適用於我。這是我最近的嘗試。

新的查詢:

$query = 
" 
SELECT MEETING.project_id, MEETING.meeting_id, MEETING_AGENDA.* 
FROM MEETING 
WHERE MEETING.project_id = $project_id 
INNER JOIN MEETING.project_id 
ON $project_id = MEETING.project_id 
"; 

我爲我的mysql缺乏知識的道歉,但任何幫助表示讚賞。

回答

1

你可以在一個單一的查詢信息與以下內容:

SELECT m.project_id, m.meeting_id, ma.* 
FROM MEETING m 
INNER JOIN MEETING_AGENDA ma ON ma.meeting_id = m.meeting_id 
WHERE m.project_id = $project_id 
+0

謝謝你的快速反應@filipesilva,就像一個魅力 – Rob