2012-08-28 90 views
0

基本上我只是想完成一个即时通讯工程,找到正确的语法用于这个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

你错过了加盟条款'WHERE customer.companyid = machine.companyid' ... –

回答

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 
+0

约翰,你是救护员先生。对不起,要问这样一个愚蠢的问题,没有睡眠会让生活变得更难。谢谢你,你已经救了我很多头痛! – user1629095

+1

训练自己在连接表时使用'ANSI SQL-92'语法。旧的'INNER JOIN'语法很容易出错,因为如果你错过了这个条件,它不会产生错误信息,但可能会做结果的笛卡尔乘积。在新版本中,您必须在'ON'子句中指定条件。 :) 不用谢。 –

+0

约翰的另一个快速问题,只是你的意见。一旦我检索到选定的数据,即时通讯将使用它与其他一些通过用户输入的数据一起发布到不同的数据库表中。这样做的最好方法是,我想通过结果获取返回的数据,将其放置在用于通过用户输入的数据的隐藏输入框中,还是有更清晰的方法来完成此操作? – user1629095