简体   繁体   中英

Select certain columns from one table and a count from another table in MySQL

I have checked out a number of answers to similar questions but still can't quite get it right.

I have two tables, Stock-Details and Goods-In . Both tables have an ID Primary Key. The column value that matches them is PrimarySKU (in Stock-Details and SKU (in Goods-In ).

So, my first query might be:

"SELECT `id`,`Nominal`,`OnOrder`,`PrimarySKU` FROM `Stock-Details`
    WHERE 'Nominal` < '10'"

And my second query would be:

"SELECT COUNT FROM `Goods-In`
    WHERE `UsedByOrderNumber`=''
    AND `SKU`= `PrimarySKU` (From My First Table.)"

How can I combine these into a single fast query that will give me all the columns in Stock-Details and the count of the rows in Goods-In where the UsedByOrderNumber is empty or used or whatever?

You can do this by getting a count by SKU where the UsedByOrderNumber is null in a subquery, then join that to your Stock-Details table:

SELECT
    t1.id,
    t1.nominal,
    t1.onorder,
    t1.primarySku
    t2.recordcount

FROM
    stock-details t1
    LEFT OUTER JOIN 
        (
            SELECT 
                SKU, 
                count(*) as recordcount 
            FROM Goods-In 
            WHERE UsedByOrderNumber IS NULL 
            GROUP BY SKU
        ) t2 ON
    t1.primarySku = t2.SKU
WHERE   
    t1.Nominal < 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM