在 PHP 中组合 sql 查询

Posted

技术标签:

【中文标题】在 PHP 中组合 sql 查询【英文标题】:Combining sql queries in PHP 【发布时间】:2012-08-30 03:02:18 【问题描述】:

您好,目前正在使用此代码

   $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_ertbl_enrolltbl_erstudent_id 的主键连接,也与 tbl_section 连接一次。 tbl_ertbl_section 与 section_id 的外键相连。

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

【问题讨论】:

两件事:1.如果student_id是所有3个表中的pk,您可以使用连接语句(当然,假设您想要来自table_er的数据与来自那些您已经从登记表中获得的学生)。 2. 我希望你能防止 SQL 注入... 这是什么 a.level ?您没有在任何地方定义“a”吗? 是的 tbl_er 与 tbl_enroll 相关,是的,我将使用 mysql_real_escape_string()。一旦我学习了 mysqli,我就会继续准备好的语句。 @LaGrandMere 我的编辑不好。 好吧,很多答案都满足你的愿望,如果你使用它,请在我的添加 level = '$lvl' :) 【参考方案1】:
   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 前缀,这样在执行查询时就不会出现模糊的引用;)

【讨论】:

【参考方案2】:

你可以按照系统税来试试

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

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

否则你可以使用 Join Query .. .Join Query 更好

【讨论】:

【参考方案3】:

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'

【讨论】:

【参考方案4】:
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..

【讨论】:

【参考方案5】:

您应该join 表格。这不是关于 php,而是关于 sql。

【讨论】:

以上是关于在 PHP 中组合 sql 查询的主要内容,如果未能解决你的问题,请参考以下文章

mysql分表后组合查询

用PHP+mysql查询两个表,然后怎么样把已经查出来的两个数组合并在一起,两张表里有一个相同的字段

如何在一个 SQL Server 查询中组合不同的计数

如何在 SQL 中组合两个查询? (子查询)

SQL学习之组合查询(UNION)

组合查询时的 SQL-server 语法错误(传递查询)