我正在尝试优化我的MySQL查询,我需要一些帮助。这是我目前的查询:
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”的东西)它不起作用,我想知道它是否可以让它工作,以及如何?
感谢您的时间!
解决方案
这是我的最终查询,如果它可以帮助任何人:
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
谢谢!
答案 0 :(得分:6)
您确实需要学会使用JOIN
。这是关系查询的基本操作,就像while()
循环是大多数应用程序语言中的基本控制结构一样。
有关SQL的任何书籍或教程都应涵盖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
子句添加更多条件:
AND s.region_id = ?;
还有一条评论......我试图通过使用BETWEEN
谓词来聪明,但这可能会混淆MySQL相对简单的优化器。 MySQL可能更容易优化原始语法:
WHERE p.date_start <= DATE(NOW()) AND p.date_end >= DATE(NOW())
答案 1 :(得分:1)
SELECT A.*, B.name AS store_name, B.username as store_username, B.region_id as region_id, B.city_id AS city_id, C.name AS subcategory_name, D.name AS category_name FROM products A, stores B, categories_sub C, categories D
WHERE B.id = A.store_id AND B.id = A.subcategory_id and C.id = A.category_id AND
A.date_start <= DATE(NOW()) AND A.date_end >= DATE(NOW())