【问题标题】:SQL Query to select from a table using a WHERE clause on another table使用另一个表上的 WHERE 子句从一个表中选择的 SQL 查询
【发布时间】:2014-09-15 15:47:34
【问题描述】:

我正在尝试在 PHP 中运行此 SQL 查询:

$sql="select b.company as c, c.company, c.resellerid from billing b, customer c WHERE (b.company = c.customerid OR b.company = c.voip_account OR b.company = c.sequence) AND c.resellerid = '0' and source = 'CDR' group by b.company asc ";
$rs=mysql_query($sql,$conn);
while($result=mysql_fetch_array($rs)) {
    $sql2="select company,extension,phone,calltype,seconds,who,customer_bill,inclusive,timestamp from billing where company='".$result["c"]."' and source='CDR' ";
    $rs2=mysql_query($sql,$conn);
    $result2=mysql_fetch_array($rs2);

    echo $result["c"].' - '.$result2["company"].'<br>';
}

billing.company 可以等于以下任何一个

customer.sequence
customer.customerid
customer.voip_account

我想选择billing 表中的所有行,其中customer.resellerid = 0 和:

billing.company = customer.sequence OR billing.company = customer.customerid OR billing.company = customer.voip_account

但其返回的行中 resellerid 不等于 0

【问题讨论】:

  • khm...什么? b.company as c, c.company, c.resellerid ,顺便说一句,要在一个查询中使用多个表,您将需要内连接或左连接
  • 你数据库结构的逻辑让我无法理解。
  • 数据库是别人设计的,我只需要这个查询就可以工作
  • 问题是,在您的第二个查询中,您选择了第一个查询中刚刚找到的公司的 all CDR 帐单,并且您没有要求 resellerid = 0 的记录了。将此条件添加到您的第二个查询中,它将起作用。然而,正如 Strawberry 指出的那样:为什么有两个查询呢?

标签: php mysql sql


【解决方案1】:

我不明白为什么会有两个查询...

SELECT DISTINCT b.company b_company
              , b.extension
              , b.phone
              , b.calltype
              , b.seconds
              , b.who
              , b.customer_bill
              , b.inclusive,timestamp
              , c.company c_company
              , c.resellerid 
           FROM billing b
           JOIN customer c 
             ON b.company IN(c.company,c.voip_account,c.sequence) 
            AND c.resellerid = 0 
            AND source = 'CDR' 
          ORDER 
             BY b.company;

请注意,PHP 的 mysql_ API 早已被弃用

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2012-10-15
    相关资源
    最近更新 更多