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粉486743671
P粉486743671 2023-08-09 14:15:07
0
1
455
<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粉486743671
P粉486743671

reply all(1)
P粉038161873

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template