2012-11-02 4 views
0

a similar question on stackoverflow에게 물어 보았지만 아무데도 도착하지 않았습니다.웹 페이지에 표시하기 위해 SQL 쿼리 출력에서 ​​중복 데이터 제거

This page은 현재 내 MSSQL 서버에서 가져 오는 출력을 보여줍니다.

나는 이벤트가 발생하는 장소 정보 (이름, 주소 등) 테이블을 가지고 있습니다. 이와 별도로 일정이 잡혀있는 실제 이벤트 테이블이 있습니다 (이벤트는 하루에 여러 번 또는 여러 날에 걸쳐 발생할 수 있음). 나는이 쿼리에 해당 테이블을 조인은 쿼리 결과를 통해 루프로

<?php 
try { 
    $dbh = new PDO("sqlsrv:Server=localhost;Database=Sermons", "", ""); 
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $sql = "SELECT TOP (100) PERCENT dbo.TblSermon.Day, dbo.TblSermon.Date, dbo.TblSermon.Time, dbo.TblSermon.Speaker, dbo.TblSermon.Series, dbo.TblSermon.Sarasota, dbo.TblSermon.NonFlc, dbo.TblJoinSermonLocation.MeetingName, dbo.TblLocation.Location, dbo.TblLocation.Pastors, dbo.TblLocation.Address, dbo.TblLocation.City, dbo.TblLocation.State, dbo.TblLocation.Zip, dbo.TblLocation.Country, dbo.TblLocation.Phone, dbo.TblLocation.Email, dbo.TblLocation.WebAddress 
     FROM dbo.TblLocation RIGHT OUTER JOIN dbo.TblJoinSermonLocation ON dbo.TblLocation.ID = dbo.TblJoinSermonLocation.Location RIGHT OUTER JOIN dbo.TblSermon ON dbo.TblJoinSermonLocation.Sermon = dbo.TblSermon.ID 
     WHERE (dbo.TblSermon.Date >= { fn NOW() }) 
     ORDER BY dbo.TblSermon.Date, dbo.TblSermon.Time"; 
    $stmt = $dbh->prepare($sql); 
    $stmt->execute(); 
    $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    foreach ($stmt as $row) { 
     echo "<pre>"; 
     print_r($row); 
     echo "</pre>"; 
    } 
    unset($row); 
    $dbh = null; 
} 
catch(PDOException $e) { 
    echo $e->getMessage(); 
} 
?> 

그래서, 그것은 각 레코드에 대해 배열을 생성하고 다음과 같이 끝 :

Array 
(
    [Day] => Tuesday 
    [Date] => 2012-10-30 00:00:00.000 
    [Time] => 07:00 PM 
    [Speaker] => Keith Moore 
    [Location] => The Ark Church 
    [Pastors] => Alan & Joy Clayton 
    [Address] => 450 Humble Tank Rd. 
    [City] => Conroe 
    [State] => TX 
    [Zip] => 77305.0 
    [Phone] => (936) 756-1988 
    [Email] => [email protected] 
    [WebAddress] => http://www.thearkchurch.org 
) 
Array 
(
    [Day] => Wednesday 
    [Date] => 2012-10-31 00:00:00.000 
    [Time] => 07:00 PM 
    [Speaker] => Keith Moore 
    [Location] => The Ark Church 
    [Pastors] => Alan & Joy Clayton 
    [Address] => 450 Humble Tank Rd. 
    [City] => Conroe 
    [State] => TX 
    [Zip] => 77305.0 
    [Phone] => (936) 756-1988 
    [Email] => [email protected] 
    [WebAddress] => http://www.thearkchurch.org 
) 
Array 
(
    [Day] => Tuesday 
    [Date] => 2012-11-06 00:00:00.000 
    [Time] => 07:00 PM 
    [Speaker] => Keith Moore 
    [Location] => Fellowship Of Faith Christian Center 
    [Pastors] => Michael & Joan Kalstrup 
    [Address] => 18999 Hwy. 59 
    [City] => Oakland 
    [State] => IA 
    [Zip] => 51560.0 
    [Phone] => (712) 482-3455 
    [Email] => [email protected] 
    [WebAddress] => http://www.fellowshipoffaith.cc 
) 
Array 
(
    [Day] => Wednesday 
    [Date] => 2012-11-14 00:00:00.000 
    [Time] => 07:00 PM 
    [Speaker] => Keith Moore 
    [Location] => Faith Family Church 
    [Pastors] => Michael & Barbara Cameneti 
    [Address] => 8200 Freedom Ave NW 
    [City] => Canton 
    [State] => OH 
    [Zip] => 44720.0 
    [Phone] => (330) 492-0925 
    [Email] => 
    [WebAddress] => http://www.myfaithfamily.com 
) 

당신이 볼 수 있듯이, 방주 교회와 그와 관련된 연락 정보는 중복되어 있기 때문에, 그 배열로 작업하여 페이지에 출력 할 때, 나는 많은 내용을 보게된다.

내가 비슷한 이에 대한 결과를 얻을 수 있도록 중복 된 정보를 제거하고 싶습니다 :

The Ark Church 
Alan & Joy Clayton 
450 Humble Tank Rd. 
Conroe, TX 77305 
(936) 756-1988 
[email protected] 
http://www.thearkchurch.org 
Meetings: 
Tuesday, 2012-10-30 07:00 PM 
Wednesday, 2012-10-31 07:00 PM 

Fellowship Of Faith Christian Center 
Michael & Joan Kalstrup 
18999 Hwy. 59 
Oakland, IA 51560 
(712) 482-3455 
[email protected] 
http://www.fellowshipoffaith.cc 
Meetings: 
Tuesday, 2012-11-06 07:00 PM 

Faith Family Church 
Michael & Barbara Cameneti 
8200 Freedom Ave NW 
Canton, OH 44720 
(330) 492-0925 
http://www.myfaithfamily.com 
Meetings: 
Wednesday, 2012-11-14 07:00 PM 

그것은 반드시 (내가 특정 코드를 찾는 게 아니에요 그런 식으로 끝낼 필요가 없습니다 이러한 결과는 아니지만 중복 된 정보를 표시하지 않는 방법에 대한 개념). 나는 추가 foreach 또는 while이 그것을 할 것이라고 가정하고 있지만, 나는 <?php if ($location == $previouslocation) echo ""; ?>이라고 말하는 논리를 알아 내지 못했습니다.

+0

이것은 당신의 문제와 관련이 있는지 잘 모르겠다. 그러나 당신은 SELECT DISTINCT를 시도 했는가 ... – Dinesh

+0

나는 단지 하나의'select something' 만 사용하도록 요구하지 않았을까? – doubleJ

+0

나는 할 수 있다고 생각한다. DISTINCT TOP .. .. – Dinesh

답변

0

아마도 GROUP BY ... HAVING 문을 사용하려고 할 것입니다.

GROUP BY dbo.TblSermon.Date HAVING MIN(dbo.TblSermon.Date) 
+0

'GROUP BY'로 작업하려면 내 쿼리를 변경해야합니다. 지금까지 테스트 한 것들만 오류가 발생했습니다. 작동하려면 집계 함수를 만들어야합니다. 나는 계속할 것이다. – doubleJ

0

와우 같은

를 추가해보십시오 뭔가 ...

나는 마침내 내가 원하는 것을 달성 (그리고 엉덩이에 통증이 있었다). 나는 그것을하는 다른 방법 (그리고 아마도 더 좋은 방법)이있을 것이라고 확신합니다. 이것은 실제로 나에게 내가 원하는 패션으로 결과를 준다.

<!doctype html> 
<html> 
<head> 
<title>Events | Faith Life Church - Branson, MO</title> 
</head> 
<body> 
<h1>Events <abbr title="And">&amp;</abbr> Meetings</h1> 
<?php 
// get events from a database 
try { 
    // MSSQL has the ability to use Windows Authentication by not passing a username or password 
    $dbh = new PDO("sqlsrv:Server=localhost;Database=Sermons", "", ""); 
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    // get events from the main database 
    $getoriginalevents = "SELECT TOP (100) PERCENT dbo.TblSermon.Day, dbo.TblSermon.Date, dbo.TblSermon.Time, dbo.TblSermon.Speaker, dbo.TblSermon.Series, dbo.TblSermon.Sermon, dbo.TblSermon.Sarasota, dbo.TblSermon.NonFlc, dbo.TblJoinSermonLocation.MeetingName, dbo.TblLocation.Location, dbo.TblLocation.Pastors, dbo.TblLocation.Address, dbo.TblLocation.City, dbo.TblLocation.State, dbo.TblLocation.Zip, dbo.TblLocation.Country, dbo.TblLocation.Phone, dbo.TblLocation.Email, dbo.TblLocation.WebAddress 
     FROM dbo.TblLocation RIGHT OUTER JOIN dbo.TblJoinSermonLocation ON dbo.TblLocation.ID = dbo.TblJoinSermonLocation.Location RIGHT OUTER JOIN dbo.TblSermon ON dbo.TblJoinSermonLocation.Sermon = dbo.TblSermon.ID 
     WHERE (dbo.TblSermon.Date >= { fn NOW() }) AND (dbo.TblSermon.Notes NOT LIKE '%Not to be put on our Website%' OR dbo.TblSermon.Notes IS NULL) 
     ORDER BY dbo.TblSermon.Date, dbo.TblSermon.Time"; 
    // prepared statements are good for security and speed 
    $originalevents = $dbh->prepare($getoriginalevents); 
    $originalevents->execute(); 
    // create an array using names instead of keys ($originalevent["Location"] instead of $originalevent[1]) 
    $originalevents->setFetchMode(PDO::FETCH_ASSOC); 

    // delete the data from the temporary events table (we don't want duplicate events) 
    $dbh->query("DELETE FROM dbo.Events"); 

    // insert events into a temporary events table (the original database doesn't contain all the information so PHP creates some) 
    // this will be executed within foreach() 
    $putprocessedevent = $dbh->prepare("INSERT INTO dbo.Events (Title, Speaker, Venue, Pastors, Street, City, State, Zip, Map, Phone, Email, Website, Date) VALUES (:title, :speaker, :venue, :pastors, :street, :city, :state, :zip, :map, :phone, :email, :website, :date)"); 

    // for every record that the initial query produces... 
    foreach ($originalevents as $originalevent) { 
     // redefine the variables 
     $title = $originalevent["Location"]; 
     if ($originalevent["MeetingName"]) $title = $originalevent["MeetingName"]; 
     if ($originalevent["Sermon"]) $title = $originalevent["Sermon"]; 
     if ($originalevent["Series"]) $title = $originalevent["Series"]; 
     $speaker = $originalevent["Speaker"]; 
     // if the record ISN'T from Sarasota or the road... 
     if ($originalevent["Sarasota"] == 0 && $originalevent["NonFlc"] == 0) { 
      $venue = "Faith Life Church"; 
      $pastors = "Keith & Phyllis Moore"; 
      $street = "3701 State Highway 76"; 
      $city = "Branson"; 
      $state = "MO"; 
      $zip = "65616"; 
      $map = "http://maps.google.com/maps?q=Faith+Life+Church+Branson+MO+65616"; 
      $phone = "+1-417-334-9233"; 
      $email = "[email protected]"; 
      $website = "http://www.flcbranson.org"; 
     } 
     // if the record IS from Sarasota... 
     if ($originalevent["Sarasota"] == 1) { 
      $venue = "Faith Life Church"; 
      $pastors = "Keith & Phyllis Moore"; 
      $street = "6980 Professional Parkway East"; 
      $city = "Sarasota"; 
      $state = "FL"; 
      $zip = "34240"; 
      $map = "http://maps.google.com/maps?q=Faith+Life+Church+Sarasota+FL+34240"; 
      $phone = "+1-941-388-6961"; 
      $email = "[email protected]"; 
      $website = "http://www.flcsarasota.org"; 
     } 
     // if the record IS from the road... 
     if ($originalevent["NonFlc"] == 1) { 
      $venue = $originalevent["Location"]; 
      if ($originalevent["Pastors"]) $pastors = $originalevent["Pastors"]; 
      $street = $originalevent["Address"]; 
      $city = $originalevent["City"]; 
      $state = $originalevent["State"]; 
      $zip = substr($originalevent["Zip"], 0, -2); 
      $map = "http://maps.google.com/maps?q=" . str_replace(" ", "+", $originalevent["Location"]) . "+" . str_replace(" ", "+", $originalevent["City"]) . "+" . $originalevent["State"] . "+" . substr($originalevent["Zip"], 0 ,-2); 
      if ($originalevent["Phone"]) $phone = "+1-" . substr($originalevent["Phone"], 1, 3) . "-" . substr($originalevent["Phone"], -8); 
      if ($originalevent["Email"]) $email = $originalevent["Email"]; 
      if ($originalevent["WebAddress"]) $website = $originalevent["WebAddress"]; 
     } 

     $date = date("Y-m-d", strtotime($originalevent["Date"])); 
     if ($originalevent["Time"]) $date = date("c", strtotime(substr($originalevent["Date"], 0, -13) . $originalevent["Time"])); 

     // execute the actual insertion of new events 
     $putprocessedevent->execute(array(":title" => $title, ":speaker" => $speaker, ":venue" => $venue, ":pastors" => $pastors, ":street" => $street, ":city" => $city, ":state" => $state, ":zip" => $zip, ":map" => $map, ":phone" => $phone, ":email" => $email, ":website" => $website, ":date" => $date)); 
    } 
    // kill the last record of the array 
    unset($originalevent); 

    // get events from the temporary events database 
    $getprocessedtitles = "SELECT DISTINCT Title, MIN(EventsID) FROM dbo.Events GROUP BY Title ORDER BY MIN(EventsID)"; 
    $processedtitles = $dbh->prepare($getprocessedtitles); 
    $processedtitles->execute(); 
    // create an array using names instead of keys ($originalevent["Location"] instead of $originalevent[1]) 
    $processedtitles->setFetchMode(PDO::FETCH_ASSOC); 

    // for every record that the new query produces... 
    foreach ($processedtitles as $processedtitle) { 
     $eventtitle = $processedtitle["Title"]; 
?> 
<h2><?php echo $eventtitle; ?></h2> 
<dl> 
    <dt>Speakers</dt> 
<?php 
     // get dates from the temporary events database 
     $getprocessedspeakers = "SELECT DISTINCT Speaker, MIN(EventsID) FROM dbo.Events WHERE Title LIKE '%" . $eventtitle . "%'GROUP BY Speaker ORDER BY MIN(EventsID)"; 
     $processedspeakers = $dbh->prepare($getprocessedspeakers); 
     $processedspeakers->execute(); 
     // create an array using names instead of keys ($originalevent["Location"] instead of $originalevent[1]) 
     $processedspeakers->setFetchMode(PDO::FETCH_ASSOC); 
     foreach ($processedspeakers as $processedspeaker) { 
      $eventspeaker = $processedspeaker["Speaker"]; 
?> 
    <dd><?php echo $eventspeaker; ?></dd> 
<?php 
     } 
?> 
</dl> 
<h3>Venue Information</h3> 
<dl> 
<?php 
     // get dates from the temporary events database 
     $getprocessedinfo = "SELECT Venue, Pastors, Street, City, State, Zip, Map, Phone, Email, Website FROM dbo.Events WHERE Title LIKE '%" . $eventtitle . "%'"; 
     $processedinfo = $dbh->prepare($getprocessedinfo); 
     $processedinfo->execute(); 
     // create an array using names instead of keys ($originalevent["Location"] instead of $originalevent[1]) 
     // I used $processedinfo = $processedinfo->fetch(PDO::FETCH_ASSOC); instead of $processedtitles->setFetchMode(PDO::FETCH_ASSOC); so that I wouldn't have to do a separate array (print_r($processedtitles); shows the actual query and not the results of the query) 
     $processedinfo = $processedinfo->fetch(PDO::FETCH_ASSOC); 
     $eventvenue = $processedinfo["Venue"]; 
     $eventpastors = $processedinfo["Pastors"]; 
     $eventstreet = $processedinfo["Street"]; 
     $eventcity = $processedinfo["City"]; 
     $eventstate = $processedinfo["State"]; 
     $eventzip = $processedinfo["Zip"]; 
     $eventmap = $processedinfo["Map"]; 
     $eventphone = $processedinfo["Phone"]; 
     $eventemail = $processedinfo["Email"]; 
     $eventwebsite = $processedinfo["Website"]; 
?> 
    <dt>Venue</dt> 
    <dd><?php echo $eventvenue; ?></dd> 
    <dt>Pastors</dt> 
    <dd><?php echo $eventpastors; ?></dd> 
    <dt>Street</dt> 
    <dd><?php echo $eventstreet; ?></dd> 
    <dt>City</dt> 
    <dd><?php echo $eventcity; ?></dd> 
    <dt>State</dt> 
    <dd><?php echo $eventstate; ?></dd> 
    <dt>Zip</dt> 
    <dd><?php echo $eventzip; ?></dd> 
    <dt>Map</dt> 
    <dd><?php echo $eventmap; ?></dd> 
    <dt>Phone</dt> 
    <dd><?php echo $eventphone; ?></dd> 
    <dt>Email</dt> 
    <dd><?php echo $eventemail; ?></dd> 
    <dt>Website</dt> 
    <dd><?php echo $eventwebsite; ?></dd> 
</dl> 
<h3>Event Dates</h3> 
<ol> 
<?php 
     // get dates from the temporary events database 
     $getprocesseddates = "SELECT Date FROM dbo.Events WHERE Title LIKE '%" . $eventtitle . "%'"; 
     $processeddates = $dbh->prepare($getprocesseddates); 
     $processeddates->execute(); 
     // create an array using names instead of keys ($originalevent["Location"] instead of $originalevent[1]) 
     $processeddates->setFetchMode(PDO::FETCH_ASSOC); 
     // for every record that the new query produces... 
     foreach ($processeddates as $processeddate) { 
      $eventdate = $processeddate["Date"]; 
?> 
    <li><?php echo $eventdate; ?></li> 
<?php 
     } 
     // kill the last record of the array 
     unset($processeddate); 
?> 
</ol> 
<?php 
    } 
    // kill the last record of the array 
    unset($processedtitle); 

    // kill the database connection 
    $dbh = null; 
} 
catch(PDOException $e) { 
    echo $e->getMessage(); 
} 
?> 
</body> 
</html> 

이 결과는 HTML 렌더링

PHP 코드를 ... ...

Events & Meetings 

KCM Branson Victory Campaign 2013 
Speakers 
    Kenneth Copeland 
    Gloria Copeland 
Venue Information 
Venue 
    Faith Life Church 
Pastors 
    Keith & Phyllis Moore 
Street 
    3701 State Highway 76 
City 
    Branson 
State 
    MO 
Zip 
    65616 
Map 
    http://maps.google.com/maps?q=Faith+Life+Church+Branson+MO+65616 
Phone 
    +1-417-334-9233 
Email 
    [email protected] 
Website 
    http://www.flcbranson.org 
Event Dates 
    1. 2013-03-07T19:00:00-06:00 
    2. 2013-03-08T14:00:00-06:00 
    3. 2013-03-08T19:00:00-06:00 
    4. 2013-03-08T09:00:00-06:00 
    5. 2013-03-09T09:30:00-06:00 

Victory Family Church 
Speakers 
    Keith Moore 

Venue Information 
Venue 
    Victory Family Church 
Pastors 
    John & Michelle Nuzzo 
Street 
    21150 Route 19 
City 
    Cranberry Township 
State 
    PA 
Zip 
    16066 
Map 
    http://maps.google.com/maps?q=Victory+Family+Church+Cranberry+Township+PA+16066 
Phone 
    +1-724-453-6200 
Email 
    [email protected] 
Website 
    http://www.lifeatvictory.com 

Event Dates 
    1. 2013-08-19T19:00:00-05:00 
    2. 2013-08-20T19:00:00-05:00 
    3. 2013-08-21T19:00:00-05:00 

은 어쩌면이 경험은 다른 사람에게 도움이 될 것입니다. 이 기능을 사용하려면 거의 일 년이 걸렸습니다. 이 클리너 또는 더 쉽게 만들 수있는 것들을 게시하십시오.