结合两个表不同的标准

时间:2012-08-28 02:06:12

标签: php mysql sql

基本上我只是试图完成一个正在处理的项目,在找到用于此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
            ");

任何帮助将不胜感激, 三江源!

1 个答案:

答案 0 :(得分:1)

您当前的查询会生成笛卡尔积,因为您错过了表应该连接的条件。这是一种旧的连接语法(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

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