繁体   English   中英

组合两个表的不同条件

[英]Combining two tables different criteria

基本上,我只是想完成一个我正在处理的项目,因此很难找到用于此SQL语句的正确语法。

基本上我有两个不同的表:

Customer:
companyid
companyname
etc etc.

Machine:
machineid
model
serial
companyid

现在通常这很容易,因为我只是加入companyid,但是,这次我需要做些不同。 我需要使用客户ID来搜索来自客户表的特定数据,并使用机器ID来搜索来自计算机表的特定数据。

我非常疲倦,所以如果答案一直直盯着我,我确实道歉,但这是我一直在努力的事情,我再一次知道它很可能出错了,所以很抱歉我尝试搜索但无济于事:

$customerquery = mysql_query("
            SELECT customer.companyid, customer.companyname, 
                   customer.companyaddress, customer.postcode, 
                   customer.telephone, customer.mobile, 
                   machine.machineid, machine.model, 
                   machine.serial 
            FROM customer, machine 
            WHERE customer.companyid=$customerid AND 
                  machine.machineid=$machineid
            ");

任何帮助将不胜感激,谢谢!

您当前的查询会产生笛卡尔积,因为您错过了应在何处连接表的条件。 这是join的旧语法( SQL-89

SELECT customer.companyid, customer.companyname, 
       customer.companyaddress, customer.postcode, 
       customer.telephone, customer.mobile, 
       machine.machineid, machine.model, 
       machine.serial 
FROM   customer, machine 
WHERE  customer.companyid = $customerid AND 
       machine.machineid = $machineid AND
       customer.companyid = machine.companyid -- you missed this one producing
                                              -- cartesian product

SQL-92新语法( SQL-92

SELECT customer.companyid, customer.companyname, 
       customer.companyaddress, customer.postcode, 
       customer.telephone, customer.mobile, 
       machine.machineid, machine.model, 
       machine.serial 
FROM   customer INNER JOIN machine 
          ON customer.companyid = machine.companyid 
WHERE  customer.companyid = $customerid AND 
       machine.machineid = $machineid

暂无
暂无

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

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