从多个表中选择的简易SQL查询?

时间:2014-12-19 12:06:53

标签: php mysql sql

您好我有关于以下示例表的问题

Table: Customer -> customer_id, customer_name

Table: Product -> product_id, product_serialnumber

Table: Customer_Product -> customer_id, product_serialnumber

现在,我如何获得customer_name,同时输入:product_id。 我将输入product_id,并想要选择购买此商品的所有customer_name(Customer_Product

我有一个查询,但它太棒了:

SELECT customer_name 
FROM Customer 
WHERE customer_id IN (
    SELECT customer_id 
    FROM Customer_Product 
    WHERE product_serialnumber IN (
        SELECT product_serialnumber 
        FROM Product 
        WHERE product_id = ?)))

还有其他简单查询吗?

2 个答案:

答案 0 :(得分:2)

您的查询没问题。编写查询的更典型方法是使用显式连接:

select c.*
from customer c join
     customer_product cp
     on c.customer_id = cp.customer_id join
     product p
     on p.product_serialnumber = cp.product_serialnumber
where p.product_id = @PRODUCT_ID;

这种方法的一个缺点是,如果某些客户多次购买该产品,您可能会遇到重复问题。当然,您可以使用select distinct

来解决此问题
select distinct c.*
from customer c join
     customer_product cp
     on c.customer_id = cp.customer_id join
     product p
     on p.product_serialnumber = cp.product_serialnumber
where p.product_id = @PRODUCT_ID;

答案 1 :(得分:2)

试试这个会起作用:

使用内部加入

    SELECT t3.`customer_name` FROM Customer_Product t1
    JOIN Product t2 ON t2.`product_serialnumber` = t1.`product_serialnumber` AND t2.`product_id`='$product_id'
JOIN Customer t3 ON t3.`customer_id` = t1.`customer_id`
    JOIN Customer t3 ON t3.`customer_id` = t1.`customer_id`

此处,$product_id由用户输入。

这是从多个表中获取数据的最简单方法。