搜尋

首頁  >  問答  >  主體

MySQL:使用主鍵和外鍵連接的兩個表,如何取得所有記錄,即使外鍵尚未填入

<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粉486743671P粉486743671572 天前509

全部回覆(1)我來回復

  • P粉038161873

    P粉0381618732023-08-10 00:25:56

    您可以使用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
    

    回覆
    0
  • 取消回覆