MySQL子查询的替代方案

时间:2016-09-01 20:02:02

标签: mysql subquery

我有3个包含列的表:

产品

id - name

shop_previews (带产品的方框)

id - name - publish(datetime)

products_shop_previews

id_product - id_shop_preview

我需要获得最新的一个shop_preview产品。可以使用子查询:

SELECT *
FROM (SELECT * FROM shop_previews WHERE publish < NOW() ORDER BY publish DESC LIMIT 1) as latest
INNER JOIN products_shop_previews psp ON psp.shop_preview_id = latest.id
INNER JOIN products p ON p.id = psp.product_id

但是,没有子查询是否可能?

1 个答案:

答案 0 :(得分:0)

我不知道我是否完全理解你想做什么,但我认为你需要子查询。如果表格由字段连接,您可以选择它:

SELECT 
    *, psp.publish as latest
FROM 
    shop_previews
INNER JOIN 
    products_shop_previews psp ON psp.shop_preview_id = latest.id
INNER JOIN 
    products p ON p.id = psp.product_id
WHERE 
    psp.publish < NOW() 
ORDER BY 
    psp.publish

这应该有用但我还没有测试过。