MySQL:使用主键和外键连接的两个表,如何获取所有记录,即使外键尚未填充
P粉486743671
P粉486743671 2023-08-09 14:15:07
0
1
456
<p>我希望找到解决办法</p> <p>我有一张带有主键stock的表</p> <pre class="brush:php;toolbar:false;">stkid (pk), name</pre> <p>第二张表(share)</p> <pre class="brush:php;toolbar:false;">price, quantity, stkid (fk)</pre> <p>我运行了这个查询,但它只显示了已经在共享记录中有记录的股票 我希望显示所有股票,即使在共享记录中没有记录</p> <pre class="brush:php;toolbar:false;">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)</pre>
P粉486743671
P粉486743671

全部回复(1)
P粉038161873

您可以使用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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板