简体   繁体   English

组合两个表的不同条件

[英]Combining two tables different criteria

basically im just trying to finish off a project im working on, having a little trouble finding the right syntax to use for this SQL statement. 基本上,我只是想完成一个我正在处理的项目,因此很难找到用于此SQL语句的正确语法。

Basically what i have two different tables: 基本上我有两个不同的表:

Customer:
companyid
companyname
etc etc.

Machine:
machineid
model
serial
companyid

Now usually this would be easy as i would just join the companyid, however, i need to do this slightly differently this time. 现在通常这很容易,因为我只是加入companyid,但是,这次我需要做些不同。 I need to return specific data from the tables of customer using the customers id to search, and specific data from the tables of machine, using the machine id to search. 我需要使用客户ID来搜索来自客户表的特定数据,并使用机器ID来搜索来自计算机表的特定数据。

Im pretty tired so i do apologise if the answer is staring me straight in the face, but heres what i was working on, again i know its more than likely wrong so i am sorry i have tried searching but to no avail: 我非常疲倦,所以如果答案一直直盯着我,我确实道歉,但这是我一直在努力的事情,我再一次知道它很可能出错了,所以很抱歉我尝试搜索但无济于事:

$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
            ");

Any help would be greatly appreciated, Thankyou! 任何帮助将不胜感激,谢谢!

Your current query produces cartesian product since you miss the condition on where the tables should be joined. 您当前的查询会产生笛卡尔积,因为您错过了应在何处连接表的条件。 This is an old syntax of join ( SQL-89 ) 这是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

New syntax of join ( SQL-92 ) 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