2014-07-24 109 views
0

Mysql版本5.1。 代碼示例:mysql select union不起作用

mysql_query("SELECT * FROM abonents WHERE `session_id`='$current_sess_id' UNION SELECT * FROM abonents_problem WHERE `session_id`='$current_sess_id' UNION SELECT * FROM abonents_stop WHERE `session_id`='$current_sess_id'"); 

運行。如果刪除 「聯盟」,例如:

mysql_query("SELECT * FROM abonents WHERE `session_id`='$current_sess_id'"); 

「WTF代碼」 永遠=):

$rez_11_one = mysql_query(
     "SELECT * FROM abonents WHERE `session_id`='$current_sess_id'" 
    ); 
    $rez_11_two = mysql_query(
     "SELECT * FROM abonents_problem WHERE `session_id`='$current_sess_id'" 
    ); 
    $rez_11_three = mysql_query(
     "SELECT * FROM abonents_stop WHERE `session_id`='$current_sess_id'" 
    ); 
    if ($rez_11_one) { 
     $rez_11 = $rez_11_one; 
    } elseif ($rez_11_two) { 
     $rez_11 = $rez_11_two; 
    } else { 
     $rez_11 = $rez_11_three; 
    } 

感謝對幫助

回答

4

參考mysql文檔UNION只適用於所有查詢返回相同的n columns

http://dev.mysql.com/doc/refman/4.1/en/union.html

所以當你使用一個選擇星號*我認爲表有不同的量列。使用select

SELECT 1,2 FROM foo UNION SELECT 1,2 FROM bar

每個查詢得到的列相同。

0

嘗試查詢,而「*」 像這樣

mysql_query("SELECT <table_column_name> FROM abonents WHERE `session_id`='$current_sess_id' UNION SELECT <table_column_name> FROM abonents_problem WHERE `session_id`='$current_sess_id' UNION SELECT <table_column_name> FROM abonents_stop WHERE `session_id`='$current_sess_id'"); 
0

您可能需要轉義字符添加到字符串,使其:

mysql_query("SELECT * FROM abonents WHERE \`session_id\`=\'$current_sess_id\' UNION SELECT * FROM abonents_problem WHERE \`session_id\`=\'$current_sess_id\' UNION SELECT * FROM abonents_stop WHERE \`session_id\`=\'$current_sess_id\'"); 
0

確保如果查詢返回相同的數根據UNION的文檔。只有當查詢返回相同的列數時纔有效。