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
2023-08-09 14:15:07
<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>
You can use the LEFT JOIN statement, which will select related rows from the
share
table, even if there are no linked rows in thestock
table.