Home  >  Q&A  >  body text

MySQL: Two tables joined using primary key and foreign key, how to get all records even if the foreign key is not populated yet

<p>I hope to find a solution</p> <p>I have a table with the primary key stock</p> <pre class="brush:php;toolbar:false;">stkid (pk), name</pre> <p>Second table (share)</p> <pre class="brush:php;toolbar:false;">price, quantity, stkid (fk)</pre> <p>I ran this query but it only showed stocks that already had a record in the shared record I want all stocks to be displayed even if there are no records in the shared record</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粉486743671437 days ago405

reply all(1)I'll reply

  • P粉038161873

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

    You can use the LEFT JOIN statement, which will select related rows from the share table, even if there are no linked rows in the stock 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
    

    reply
    0
  • Cancelreply