简体   繁体   English

从一个表中选择某些列,从MySQL中的另一个表中选择一个计数

[英]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 . 我有两个表, Stock-DetailsGoods-In Both tables have an ID Primary Key. 两个表都有一个ID主键。 The column value that matches them is PrimarySKU (in Stock-Details and SKU (in Goods-In ). 与它们匹配的列值是PrimarySKU (在Stock-DetailsSKU (在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? 如何将这些组合成一个快速查询,它将为我提供Stock-Details所有列以及Goods-InUsedByOrderNumber为空或使用的行数或其他?

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: 您可以通过获取SKU的计数来实现此目的,其中UsedByOrderNumber在子查询中为空,然后将其连接到您的Stock-Details表:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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