我想找到所有记录,即使外键还没有填充。

huangapple go评论80阅读模式
英文:

I want find all records even if not yet popoulated with foreign key

问题

表格 stock

stkid (主键), name

表格 share

price, quantity, stkid (外键)

我运行了这个查询,但它只显示已经在 share 表中有记录的股票。我想要显示所有股票,即使在 share 表中没有记录。

select name,
       0,
       sum(price*quantity) / sum(quantity) as avg,
       sum(quantity) as qty
from stock
left join share on share.stkid = stock.stkid
group by stock.stkid
英文:

Table stock:

stkid (pk), name

Table share:

price, quantity, stkid (fk)

I run this query but it shows stocks only that have records in shares already. I want to show all stocks even with no records in shares.

select name,
       0,
       sum(price*quantity) / sum(quantity) as avg,
       sum(quantity) as qty
from stock,
     share
where share.stkid = stock.stkid
group by (stock.stkid)

答案1

得分: 0

你可以使用LEFT JOIN语句,即使在share表中没有关联的行,它仍然会选择stock表中的行。

SELECT
  name,
  0,
  sum(price*quantity) / sum(quantity) as avg,
  sum(quantity) as qty
FROM stock
LEFT JOIN share ON share.stkid = stock.stkid
GROUP BY stock.stkid
英文:

You can use a LEFT JOIN statement, it will still select the lines from the stock table even if there is no linked row in the share table.

SELECT
  name,
  0,
  sum(price*quantity) / sum(quantity) as avg,
  sum(quantity) as qty
FROM stock
LEFT JOIN share ON share.stkid = stock.stkid
GROUP BY stock.stkid

huangapple
  • 本文由 发表于 2023年8月9日 15:21:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定