[英]Select all columns from a table that matches an id in another table
I have a table structure like this 我有这样的表结构
Customer 顾客
CustomerID|CustomerName|CustomerPhone|CustomerAddress
123 |Jason |219632369 |4 pine street
485 |David |219632369 |4 pine street
586 |Ramsay |219632369 |4 pine street
779 |Jacob |219632369 |4 pine street
Order 订购
OrderID|CustomerID|ItemCode|ItemDesc
425 |123 |456 |Intel i7
427 |123 |456 |Intel i7
428 |485 |456 |Intel i7
429 |123 |456 |Intel i7
430 |485 |456 |Intel i7
431 |123 |456 |Intel i7
Expected output 预期产量
CustomerID|CustomerName|CustomerPhone|CustomerAddress
123 |Jason |219632369 |4 pine street
485 |David |219632369 |4 pine street
I want to select all the columns from the customer table who have entries in orders table using the customerid 我想使用customerid从customer表中选择在订单表中具有条目的所有列
This is what I tried 这是我尝试过的
select *
from customer
where customerid = (select customerid
from order);
But this doesn't work. 但这是行不通的。
Use Exists
to search such customers since it avoids problems in case some order does not have a customerid
specified. 使用“
Exists
搜索此类客户,因为这样可以避免某些订单未指定customerid
ID的问题。 If some customerid
is null
in order
the IN
predicate is evaluated to unknown and it means that the no customer is returned. 如果某些
customerid
是null
的order
的IN
谓词进行评估,以未知的,这意味着返回没有客户。
select *
from customer c
where exists (
select 1
from "order" o
where o.customerid = c.customerid
)
Try to avoid using keywords for table names ( order
), it may cause unexpected troubles when writing SQL code. 尽量避免在表名(
order
)中使用关键字,否则在编写SQL代码时可能会引起意外的麻烦。
您也可以使用内部联接来完成此操作,这只是一个附加解决方案:
select distinct cust.* from Customer cust inner join Order o on cust.CustomerID = o.CustomerID
Use the IN
operator: 使用
IN
运算符:
select *
from customer
where customerid in (select customerid from order)
Try this 尝试这个
You have can create aliases for the tables, this is equal: select all from customer where customerid exists on orders 您可以为表创建别名,这等同于:从订单中存在customerid的客户中选择所有别名
Select A.* from customer a, order b where a.customerid = b.customerid 从客户a中选择A. *,订购b,其中a.customerid = b.customerid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.