这样子查询最有效吗?

时间:2018-11-12 15:59:46

标签: mysql join subquery

这是我的代码,我试图获取按'Village bookshop''27/09/2018'上的顺序显示的图书总价

相关表格

book(isbn, title, authorID, genre, pubYear, publisher, rrPrice, avgRating)

bookShop(shopNo, shopName, street, city, county)

orders(orderNo, sNo, oDate, salesRep)

orderDetails(oNo, bookISBN, quantity) 

我的问题是,有比子查询更有效的方法吗?

SELECT sum(rrPrice)
FROM   book 
WHERE  isbn in(
    SELECT bookISBN
    FROM   orderDetails INNER JOIN orders ON orderNO = oNO 
           INNER JOIN bookShop on sNO = shopNo
    WHERE  shopName = 'Village bookshop' and oDate='27/09/2018'
)

3 个答案:

答案 0 :(得分:0)

您的查询有很多选择。我建议使用EXISTS子句,因为它只返回逻辑值,总是比比较字符串或数字快。

它将是这样的:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
    provider.Mappings[".webmanifest"] = "application/manifest+json";

    app.UseStaticFiles(new StaticFileOptions()
    {
        ContentTypeProvider = provider
    });

    app.UseMvc();
}

这只是可读性和复杂性的问题,因为您不会脱离IJ。您也可以执行IJ,而无需执行任何子查询,这也将是正确的。

答案 1 :(得分:0)

通常,子查询上的内部联接要比同一子查询上的IN子句更好,因此请尝试使用

    SELECT sum(rrPrice)
    FROM   book 
    INNER JOIN (
        SELECT bookISBN
        FROM   orderDetails 
        INNER JOIN orders ON orderNO = oNO 
        INNER JOIN bookShop on sNO = shopNo
        WHERE  shopName = 'Village bookshop' and oDate='27/09/2018'
    ) t on book.isbn = t.bookISBN

查询仅与问题有关,是否有一种最有效的方式来处理IN子句..并且不评估与您的数据内容相关的方面

答案 2 :(得分:-2)

编辑:阅读后,这是的最佳使用方法。留给其他人学习。

您可以从多个表中进行选择,并在“ WHERE”子句中处理更多的逻辑。与此类似:

SELECT sum(rrPrice)
FROM book, bookShop, orders, orderDetails
WHERE book.isbn = orderDetails.bookISBN AND orderDetails.oNo = orders.orderNo AND bookShop.shopNo = orders.sNo and shopName = 'Village bookshop' and oDate='27/09/2018'