MYSQL优化&问题

2022-01-23 00:00:00 optimization sql subquery mysql

我正在尝试优化我的 MySQL 查询,我需要一些帮助.这是我当前的查询:

I am trying to optimize my MySQL queries and I need some help. Here is my current query :

SELECT *,
       (SELECT name FROM stores WHERE id = products.store_id) AS store_name,
       (SELECT username FROM stores WHERE id = products.store_id) AS store_username,
       (SELECT region_id FROM stores WHERE id = products.store_id) AS region_id,
       (SELECT city_id FROM stores WHERE id = products.store_id) AS city_id,
       (SELECT name FROM categories_sub WHERE id = products.subcategory_id) AS subcategory_name,
       (SELECT name FROM categories WHERE id = category_id) AS category_name
FROM products
WHERE date_start <= DATE(NOW()) AND date_end >= DATE(NOW())

我很确定它会更快.

我也有一个问题,当我尝试按 region_id 选择所有产品时(通过添加AND region_id = MYID"之类的内容)它不起作用,我想知道是否有可能让它工作,以及如何工作?

I also have a problem, when I try to select all products by region_id (by adding something like "AND region_id = MYID") it doesn't work, and I wonder if it's possible to get it working, and how?

感谢您的宝贵时间!

解决方案

这是我的最后一个问题,如果它可以帮助任何人:

Here is my final query, if it can help anyone :

SELECT p.*,
       s.name AS store_name,
       cs.name AS subcategory_name,
       cat.id AS category_id, cat.name AS category_name,
       c.id AS city_id, c.name AS city_name,
       r.id AS region_id, r.name AS region_name
  FROM products p
       JOIN stores s ON (s.id = p.store_id)
       JOIN categories_sub cs ON (cs.id = p.subcategory_id)
       JOIN categories cat ON (cat.id = cs.category_id)
       JOIN cities c ON (c.id = s.city_id)
       JOIN regions r ON (r.id = c.region_id)
  WHERE DATE(NOW()) BETWEEN p.date_start AND p.date_end

谢谢!

推荐答案

你真的需要学会使用JOIN.它是关系查询的基本操作,就像 while() 循环是大多数应用程序语言中的基本控制结构一样.

You really need to learn to use JOIN. It's a fundamental operation for relational queries, just as a while() loop is a basic control structure in most application languages.

任何有关 SQL 的书籍或教程都应涵盖 JOIN.

Any book or tutorial on SQL should cover JOIN.

SELECT p.*, 
 s.name AS store_name, s.username AS store_username, 
 s.region_id, s.city_id,
 cs.name AS subcategory_name,
 c.name AS category_name
FROM products p
 JOIN stores s ON (s.id = p.store_id)
 JOIN categories c ON (c.id = p.category_id)
 JOIN categories_sub cs ON (cs.id = p.subcategory_id)
WHERE DATE(NOW()) BETWEEN p.date_start AND p.date_end

现在您可以在 WHERE 子句中添加更多条件:

Now you can add more conditions to your WHERE clause:

  AND s.region_id = ?;

<小时>

还有一条评论...我试图通过使用 BETWEEN 谓词来变得聪明,但这可能会混淆 MySQL 相对简单的优化器.MySQL 可能更容易优化您的原始语法:


One more comment... I was trying to be clever by using the BETWEEN predicate, but this might confuse MySQL's relatively simple optimizer. MySQL might have an easier time optimizing your original syntax:

WHERE p.date_start <= DATE(NOW()) AND p.date_end >= DATE(NOW())

相关文章