Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从一个表中获取行,再加上从相关表中获取计数_Sql_Database_Postgresql - Fatal编程技术网

Sql 从一个表中获取行,再加上从相关表中获取计数

Sql 从一个表中获取行,再加上从相关表中获取计数,sql,database,postgresql,Sql,Database,Postgresql,我正在尝试构建一个SQL查询,在其中获取一个表的信息(where shops.shop\u domain=X)以及客户表的计数where customers.product\u id=4242451) shops表中没有product.id,但是customers表中有shop\u域,因此我尝试进行某种联接 我主要想返回以下内容: 商店id 商店名称 shops.shop\u域 CUSTOMERS.product_id='4242451' 下面是我在这个问题上的不太可爱的尝试。 我想我的想法

我正在尝试构建一个SQL查询,在其中获取一个表的信息(
where shops.shop\u domain=X
)以及客户表的计数
where customers.product\u id=4242451

shops表中没有
product.id
,但是customers表中有
shop\u域
,因此我尝试进行某种联接

我主要想返回以下内容:

  • 商店id
  • 商店名称
  • shops.shop\u域
  • CUSTOMERS.product_id='4242451'
下面是我在这个问题上的不太可爱的尝试。 我想我的想法是对的(也许…),但我无法集中精力构建这个查询

SELECT shops.id, shops.name, shops.shop_domain, COUNT(customers.customer_id) 
FROM shops 
LEFT JOIN customers ON shops.shop_domain = customers.shop_domain 
WHERE shops.shop_domain = 'myshop.com' AND 
      customers.product_id = '4242451' 
GROUP BY shops.shop_id
相关数据库模式:

shops:
id, name, shop_domain

customers: 
id, name, product_id, shop_domain

你很接近。
customers
上的条件需要放在
on
子句中,因为这是一个
左连接
customers
是第二个表:

SELECT s.id, s.name, s.shop_domain, COUNT(c.customer_id)
FROM shops s LEFT JOIN
     customers c
     ON s.shop_domain = c.shop_domain AND c.product_id = '4242451'
WHERE s.shop_domain = 'myshop.com'
GROUP BY s.id, s.name, s.shop_domain;

我也倾向于将
分组中的所有三列都包含在
中,尽管Postgres(和ANSI/ISO标准)只喜欢
id
,如果它被声明为表中的主键。

A相关子查询应该更便宜(更简单):

SELECT id, name, shop_domain
     , (SELECT count(*)
        FROM   customers
        WHERE  shop_domain = s.shop_domain
        AND    product_id = 4242451) AS special_count
FROM   shops s
WHERE  shop_domain = 'myshop.com';
这样,您只需要在子查询中进行聚合,而不必担心对外部查询产生不希望的影响


假设
product\u id
是一个,所以我使用(
4242451
)而不是字符串文字
'4242451'
——否则可能会导致问题。

Wow。那是难以置信的快。我只是把它放进去了,我相信它工作得很好。。。。给我几分钟时间来测试一下。非常感谢戈登,你太棒了。非常感谢戈登,非常感谢。祝你有美好的一天。在这种情况下,博士后只对PK感到高兴<代码>唯一
是不够的(没有完全实现标准)。@ErwinBrandstetter。谢谢你的澄清。我现在看到,文档中不仅提到了“函数依赖性”,还给出了“主键”作为定义。