数据库查询选择客户信息

wkyowqbh  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(284)

我有一个问题,我试图从数据库中检索用户的数据,其中包含以下信息:
我需要的是购买参考号为1800和1898的产品的客户的姓名、姓氏和电子邮件。2018年5月18日之前。
我尝试了以下查询:

select
ps_customer.firstname, lastname , email
from
ps_customer
inner join
ps_product
where
ps_product.reference in (1800,1898) and ps_product.date_add >= 2018-05-18

但这只提供了所有客户的所有信息,而这不是我想要的。

nqwrtyyt

nqwrtyyt1#

我宁愿使用两个表共同拥有的唯一键(无论是客户id还是产品id,取决于两个表中可用的列)将ps\u product表连接到ps\u customer表,然后将我的限制放在一个单独的where子句中。在你的where子句中,也要在单个报价中注明日期:
如。

select ps_customer.firstname, lastname , email
from ps_customer c
inner join ps_product p on c.customerid = p.customerid
where ps_product.reference in (1800,1898) and ps_product.date_add >= '2018-05-18';
bksxznpy

bksxznpy2#

假设所有值都来自第一个表ps\u customer,则必须使用table.column为所有值指定它们所在的表,而您只处理了第一个值。
为了更好的可读性,您应该为表提供一个带有as的别名,如下例所示。
您还必须在on语句中指定列要连接的属性。两个表的值必须相同。

select cus.firstname, cus.lastname , cus.email 
from ps_customer AS cus
inner join ps_product AS prod
ON cus.uniqueKey = prod.uniqueKey
where prod.reference in (1800,1898) and prod.date_add >= 2018-05-18;

编辑:通过添加图片,我假设您有一个销售表,该表引用了一个客户和一个产品。我认为构造此查询的最佳方法是:

SELECT customer.firstname, customer.lastname, customer.email
FROM ps_product_sale AS sale               (if this is the table with sales records)
INNER JOIN ps_product AS product
      ON sale.id_product = product.id_product
INNER JOIN ps_customer AS customer
      ON customer.id_customer = sale.id_customer
WHERE product.reference in (1800,1898) 
      AND product.date_add >= 2018-05-18;

相关问题