我正在尝试从两个表中提取数据,而且我一直在阅读这里和Google上的JOIN,但似乎没有任何工作正常。
我需要从客户表和自定义表中提取。这是客户表格布局:
CustomerID: int PRIMARY KEY UNIQUE
Customername: varstring
Customeraddress: varstring
Customertype: int
Customerdescription: text
示例:
CustomerID: 1
CustomernName: John Smith
Customeraddress: 1 Fake St., New York, New York, 11111
Customertype: 1
Customerdescription: Customer makes a monthly purchase of this and that.
以下是客户类型布局:
TypeID: int PRIMARY KEY UNIQUE
Typetitle: varstring
Typedescription: text
示例:
TypeID: 1
Typetitle: In good standing
Typedescription: These customers are in good standing and owe nothing.
customer表中的Type字段显然应该与customertype表中的Type字段相对应。所以,如果我需要知道所有John Smith的数据,我想在一个查询中:
CustomerID: 1
Customername: John Smith
Customeraddress: 1 Fake St. New York, New York, 11111
Typetitle: In good standing
Customerdescription: Customer makes a monthly purchase of this and that.
障碍是,有时Customertype为0,它与customertype表中的任何记录都不对应。他们的类型未定义。
我已经在各个地方读过JOIN,但我似乎无法进行查询,以处理CustomerID = TypeID或CustomerID = 0的位置。有没有人有任何建议或知道查询是什么?
答案 0 :(得分:1)
这应该有效:
SELECT c.CustomerID, c.Customername, c.Customeraddress, t.Typetitle, c.Customerdescription
FROM Customer c
LEFT JOIN customertype t ON c.Customertype = t.TypeID
左连接不会过滤掉第二个表中没有匹配项的内容。您可以从两个表中添加所需的列。
答案 1 :(得分:0)
您可以在join子句中使用OR
表达式。在您的情况下,您需要进行左连接。有点像...
SELECT * FROM Customer LEFT JOIN Type ON Customer.Customertype = Type.TypeID OR Customer.Customertype = 0