2011-03-03 60 views
0

夥計們我有這個查詢,得到一個關鍵字,並在數據庫中搜索一系列文章,根據關鍵字查詢結果顯示,然後我需要根據我得到的ID和顯示它獲取有關這些文章的信息。查詢沒有完成,有人可以幫我清理下一個代碼並改進它嗎?MySQL:PHP在查詢的同時又用查詢,如何提高?

謝謝

$cleanKeyword = str_replace("+", " ", $keyword); 
$i = mysql_query("SELECT IdNorma FROM $cpalabras WHERE Descripcion = '$cleanKeyword'"); 
    while($materia = mysql_fetch_array($i)){ 
     // storing idNorma into a variable 
     $IdNorma = $materia['IdNorma']; 
    $SQL = "SELECT n.*, j.Descripcion as jurisdiccion, 
      t.Descripcion as tipo, 
      date_format(n.FechaDesde,'%d') as dia, 
      date_format(n.FechaDesde,'%m') as mes, 
      date_format(n.FechaDesde,'%Y') as anio 
      FROM c_normas as n, c_jurisdiccion as j, c_tiponorma as t, c_materia as m 
      WHERE 1=1 "; 
    $SQL .= "AND n.IdNorma = '$IdNorma' "; 
    $SQL .= "ORDER BY Fechadesde DESC LIMIT 300"; 

    var_dump($SQL); 
    $a = mysql_query($SQL); 
     if(mysql_num_rows($a) > 0) { 
     while($row = mysql_fetch_array($a)){ ?> 
      <tr style="display:inline-block;width:100%;border-bottom:1px solid #E3E6EB;padding:4px 0;font-size: 10px;" class="listaEventoUnicoTr" id="quickSearchTr"> 
      <td width="120" align="left" id="searchable"><strong><?php echo fromDB($row['tipo']); ?></strong></td> 
      <td width="90" align="left"><a href="http://www.ips.com.ar/normmunipC/IPS_Municipal_files/files/<?php echo fromDB($row['Archivo']); ?>" target="_blank"><?php echo fromDB($row['Numero']); ?></a></td> 
      <td width="90" align="left" id="searchable"><?php echo fromDB($row['dia'])."-".fromDB($row['mes'])."-".fromDB($row['anio']); ?></td> 
      <td width="255" align="left" style="padding-top:4px;padding-bottom:4px;" id="searchable"><?php echo fromDB($row['Descripcion']); ?></td> 
      </tr> 
     <?php } //while 
     } else { //if ?> 
      <tr style="display:inline-block;width:100%;border-bottom:1px solid #E3E6EB;padding:4px 0;font-size: 10px;" class="listaEventoUnicoTr" id="quickSearchTr"> 
      <td width="500" align="center" colspan="4"> No hay resultados.</td> 
      </tr> 


     <?php } // else 

    }// /while ids 

謝謝你們!

+0

開始學習如何使用JOIN的SQL查詢 – 2011-03-03 13:21:48

回答

2

這應該可以幫助您在正確的方向前進:

SELECT n.*, j.descripcion as jurisdiccion, t.Descripcion as tipo, date_format(n.FechaDesde,'%d') as dia, date_format(n.FechaDesde,'%m') as mes, date_format(n.FechaDesde,'%Y') as anio 

FROM c_normas as n 

LEFT JOIN $cpalabras on $cpalabras.IdNorma = n.IdNorma 

ORDER BY Fechadesde DESC LIMIT 300 
1

2個選擇:

  1. 使用JOIN加入數據源。在這種情況下,您只需要1個查詢,但我不太確定它會是什麼樣子,因爲從c_normas as n, c_jurisdiccion as j, c_tiponorma as t, c_materia as m中選擇看起來很奇怪/錯誤。
  2. 在第一個查詢從$cpalabras獲取數據後,建立「有效」 $IdNorma值列表,然後做一個查詢,以便從c_normas as n, c_jurisdiccion as j, c_tiponorma as t, c_materia as m選擇所有必要的數據,像成才(..) where n.IdNorma in (1, 2, 3),而不是(..) where n.IdNorma = 1