2015-09-04 43 views
0

我發現很難在查詢中加入多個select語句。 如果我選擇一個單一的查詢,它工作正常,但聯合命令加入選擇語句什麼也沒有顯示。我在做什麼可能是錯誤的。如何在查詢中使用多個select語句

$sel=mysql_query ("SELECT * 
FROM studentmark join 
    student 
    ON studentmark.student_id = student.username join 
    subject 
    ON subject.code = studentmark.code 
where student.username='$name' AND studentmark.YEAR = '$ya' AND 
    studentmark.TERM = 'THIRD') 
//it works fine without using the union for a single query but joining the query there is nothing display 

UNION(SELECT TOTAL AS secondterm 
FROM studentmark 
    JOIN subject ON subject.code=studentmark.code 
WHERE studentmark.student_id='$name' 
AND studentmark.YEAR='$ya' 
AND studentmark.TERM = 'SECOND')UNION(SELECT TOTAL AS firstterm 
FROM studentmark 
    JOIN subject ON subject.code=studentmark.code 
WHERE studentmark.student_id='$name' 
AND studentmark.YEAR='$ya' 
AND studentmark.TERM = 'FIRST'"); 

$fetch=mysql_fetch_array($sel); 
$count=mysql_num_rows($sel); 
+0

您unioning一個不同的列數:'SELECT *'和'SELECT達爾secondterm'。這不起作用。可能的解決方案:http://stackoverflow.com/questions/2309943/unioning-two-tables-with-different-number-of-columns –

+0

聯盟只適用於單個表不適用於2表 – user5189527

+0

您的代碼很難閱讀,請格式好一點。在聯合中使用多少表並不重要,但聯合中的每個查詢的列數必須匹配:'(Select * from studentmark ...)UNION(選擇TOTAL AS作爲第二項FROM studentmark ... 。)UNION(選擇總計作爲firstterm FROM studentmark ...)第二個和第三個查詢只返回一列,但第一個返回更多的列。 –

回答

0
$sel=mysql_query ("SELECT YEAR, TERM, CODE, student_id, ContAss20, AsgClassWk10, Test2nd10,Exam60, Total,tname 
FROM studentmark join 
    student 
    ON studentmark.student_id = student.username join 
    subject 
    ON subject.code = studentmark.code 
where student.username='$name' AND studentmark.YEAR = '$ya' AND 
    studentmark.TERM = 'THIRD') 
//it works fine without using the union for a single query but joining the query there is nothing display 

UNION(SELECT null, null, null, null, null, null, null,null, Total as secondterm, null 
FROM studentmark 
    JOIN subject ON subject.code=studentmark.code 
WHERE studentmark.student_id='$name' 
AND studentmark.YEAR='$ya' 
AND studentmark.TERM = 'SECOND')UNION(SELECT TOTAL AS firstterm 
FROM studentmark 
    JOIN subject ON subject.code=studentmark.code 
WHERE studentmark.student_id='$name' 
AND studentmark.YEAR='$ya' 
AND studentmark.TERM = 'FIRST'"); 

$fetch=mysql_fetch_array($sel); 
$count=mysql_num_rows($sel); 
相關問題