繁体   English   中英

在PHP中组合SQL查询

[英]Combining sql queries in PHP

您好目前使用此代码

   $qry_display = "
SELECT 
    student_id,
    fname,
    sex,
    lname,
    mname,
    level,
    photo,
    birth_date,
    birth_place,
    address,
    father,
    father_occupation,
    father_phone,
    father_company,
    father_degree,
    mother,
    mother_occupation,
    mother_phone,
    mother_company,
    mother_degree,
    adviser_id 
from 
    tbl_enroll 
where 
    student_id='$id' 
    AND level='$lvl'

";
    $sql_display = mysql_query($qry_display) or die (mysql_error());

上面的代码从tbl_enroll获取大部分数据。 现在我想获取一些关于tbl_er的数据。 tbl_enrolltbl_erstudent_id的主键连接,也连接到tbl_section tbl_ertbl_section与section_id的外键相连。

到目前为止,我一直在考虑做多个SQL查询并使用一个mysql_query触发器,但它不会工作,因为触发器不能使用三个SQL查询。

只需JOIN三个表:

SELECT t1.*, t2.*, t3.*
from tbl_enroll t1
JOIN tbl_el t2 ON t1.student_id = t2.student_id
JOIN tbl_section t3 ON t2.section_id = t3.section_id
where student_id='$id' AND a.level='$lvl'

你应该加入这些表格。 这不是关于php而是关于sql。

您可以尝试按照systax

select tb1.filds,tb2.fields ... from table1 as tb1, table2 as tb2 .. where tb1.id = tb2.id and tb2.id  = tb3.id ...

在哪里条件必须正确检查。

否则你可以使用加入查询... .Join查询更好

   SELECT te.XXX,tr.YYYY,ts.ZZZ, ..... 
   from tbl_enroll te 
   inner join tbl_er tr on tr.student_id = te.student_id
   inner join tbl_section ts on ts.section_id = te.section_id
   where student_id='$id' and level='$lvl';

您可以在查询开头选择te,tr或ts中的任何字段。 不要忘记在te,tr或ts字段前加上前缀,以便在执行查询时没有不明确的引用;)

Combining two queries..

SELECT t1.* FROM tbl_er as t1, tbl_enroll as t2
WHERE t1.student_id= t2.student_id ORDER BY id DESC

您必须在两个表中定义学生ID。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM