替代子查询的方法

时间:2011-08-02 15:20:14

标签: php mysql

我现在正在这样做,但希望SO的好人看看它。它可以工作,但我认为使用子查询/嵌套查询会更快但仍在学习MySQL查询

非常感谢嵌套/子查询方法。 感谢

//////
//Get Events

$query_display_events  = "SELECT E.id, E.er_mem_id, E.er_ev_name, E.er_ev_status FROM ".ER_EVENTS_MAIN." E WHERE E.er_ev_status=1 AND E.er_mem_id = '$user_id'";


$e_result = mysql_query($query_display_events) or die(header("Location: /er_error_page?error_msg=1"));

// print table
$data = '<table width="60%" border="0" cellpadding="0" cellspacing="0" class="bord_display_events">
<th>Event Name <th>Description<th>Starts<th>Ends<th>Status

';


while($e_row = mysql_fetch_assoc($e_result)) {


    //Get Events Time

$query_get_ev_time  = "SELECT T.er_ev_id, T.er_ev_start_date, T.er_ev_end_date FROM ".ER_EVENTS_TIME." T WHERE T.er_ev_id = '$e_row[id]'";


$t_result = mysql_query($query_get_ev_time) or die(header("Location: /er_error_page?error_msg=1"));
    while($t_row = mysql_fetch_assoc($t_result)) {

                    //Format date
                    $ev_start_time = date('Y-m-d g:i a', $t_row['er_ev_start_date']); 
                    $ev_end_time = date('Y-m-d g:i a', $t_row['er_ev_end_date']);


  $data .= "\n<tr>
              \n\t<td><b><a href=/readnews/$e_row[id]> $e_row[er_ev_name]</a></b>
              <td><font class=font_news_display_body>".mb_wordwrap(substr($e_row['er_ev_name'],0,170))."..."."
              <td><font class=font_news_display_body>$ev_start_time
              <td><font class=font_news_display_body>$ev_end_time

      \n</tr>
      ";

  }
}
$data .= "\n</table>\n";
////////

2 个答案:

答案 0 :(得分:1)

SELECT E.id, E.er_mem_id, E.er_ev_name, E.er_ev_status, 
       T.er_ev_id, T.er_ev_start_date, T.er_ev_end_date 
    FROM ER_EVENTS_MAIN E 
        INNER JOIN ER_EVENTS_TIME T 
            ON E.id = T.er_ev_id
    WHERE E.er_ev_status = 1 
        AND E.er_mem_id = '$user_id'

答案 1 :(得分:1)

为什么不在桌面上使用LEFT JOIN?

SELECT T.er_ev_id, T.er_ev_start_date, T.er_ev_end_date FROM `T` LEFT JOIN `E` ON (`T`.`er_ev_id`=`E`.`er_ev_id`) WHERE `T.er_ev_id`='something'

很抱歉,查询本身可能不适合您的表格布局。您可能只想阅读http://dev.mysql.com/doc/refman/5.0/en/join.html

你也有不同类型的连接(LEFT,RIGHT,INNER等),这些连接带来了与连接表不同的条件; - )