【发布时间】:2013-07-29 11:48:29
【问题描述】:
我的 SQL 查询有问题。我正在尝试查询数据库以从 3 个不同的表中获取数据,其中应用了一个表条件。 在第二个条目上,它正确显示了结果,但在第一个条目上,它没有显示应用条件的表格的结果。
这是我的查询:
SELECT
`".PRODUCTS."`.*,
`".CATEGORIES."`.*,
`q_prices`.*
FROM
`".PRODUCTS."`
LEFT JOIN
`".CATEGORIES."`
ON
`".PRODUCTS."`.`category_id` = `".CATEGORIES."`.`category_id`
INNER JOIN(
SELECT
`".PRICES."`.*
MAX(`".PRICES."`.`price_modified`) modified
FROM
`".PRICES."`
GROUP BY
`".PRICES."`.`product_id`
) `q_prices`
ON
`".PRODUCTS."`.`product_id` = `q_prices`.`product_id`
这是它返回的内容:
Array
(
[0] => stdClass Object
(
[product_id] => 1
[product_name] => Test product
[product_alias] => test-product
[category_id] => 1
[product_created] => 2013-07-29 11:36:51
[product_modified] => 2013-07-29 11:36:51
[category_name] => Test categorie
[category_alias] => test-categorie
[category_parent] => wonenplaza.nl
[category_created] => 2013-07-29 11:39:29
[category_modified] => 2013-07-29 11:39:29
[price_id] => 1
[price_amount] => 25.00
[price_tax] => 21
[price_created] => 2013-07-29 11:38:18
[price_modified] => 2013-07-29 11:38:18
[modified] => 2013-07-29 11:38:52
)
[1] => stdClass Object
(
[product_id] => 2
[product_name] => Priva Blue ID
[product_alias] => test-product2
[category_id] => 1
[product_created] => 2013-07-29 12:18:54
[product_modified] => 2013-07-29 12:18:54
[category_name] => Test categorie
[category_alias] => test-categorie
[category_parent] => wonenplaza.nl
[category_created] => 2013-07-29 11:39:29
[category_modified] => 2013-07-29 11:39:29
[price_id] => 4
[price_amount] => 20.00
[price_tax] => 21
[price_created] => 2013-07-29 12:19:11
[price_modified] => 2013-07-29 12:19:11
[modified] => 2013-07-29 13:30:05
)
)
我认为这与 LEFT JOIN 查询中指定的限制有关,但我不确定。我不知道如何查询数据库以获得这些结果。
提前致谢(:
【问题讨论】:
-
请问您想通过最后一次加入来实现什么目标?查找每件商品的最新价格?
-
是的,我想保留价格历史记录,但在此查询中,我试图获取产品的最新价格。
-
没有 DESC 限制。 DESC 与 ORDER BY 相关。
-
你真的有没有product_ID的产品吗?在我看来,您试图加入一个字段(products.product_ID),该字段在您用作主键的内容中具有空值。然后,这会导致有效加入类别,但找不到这样的价格记录。我假设第二条记录真的是你想要的。因此,要么将
where product_ID is not null添加到 where 子句,要么修复数据,使 products.product_ID 中不存在 null(也许是空格?) -
正确,更新了第一篇文章。虽然我的问题仍然存在。