【问题标题】:how to use multiple select statement in a query如何在查询中使用多个选择语句
【发布时间】:2015-09-04 08:51:12
【问题描述】:

我发现很难在一个查询中加入多个 select 语句。 如果我选择一个查询,它可以正常工作,但使用 union 命令加入 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);

【问题讨论】:

  • 您正在合并不同数量的列:Select * SELECT TOTAL AS secondterm 。这行不通。可能的解决方案:stackoverflow.com/questions/2309943/…
  • 联合只适用于单张表,不适用于2张表
  • 您的代码难以阅读,请格式化好一点。无论您在联合中使用多少表,但联合中每个查询的列数必须匹配:(Select * from studentmark ...) UNION (Select TOTAL AS secondterm FROM studentmark ....) UNION (SELECT TOTAL AS firstterm FROM studentmark ...) 第二个和第三个查询只返回一列,但第一个返回更多列。
  • $sel=mysql_query ("SELECT test1,test2,test3,test4 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')

标签: select join union


【解决方案1】:
$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);

【讨论】:

    猜你喜欢
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2011-01-03
    • 2013-11-14
    • 1970-01-01
    • 2013-03-01
    相关资源
    最近更新 更多