MySql查询按另一个表中存在的顺序排序

时间:2013-12-07 12:23:10

标签: mysql sql

我有三张桌子(product,product_info和specials)

products(id, created_date)
product_info(product_id, language, title, .....)
specials(product_id, from_date, to_date)

product_id是引用产品ID的外键

在搜索产品时,我想按特殊产品订购此搜索...

这是我的尝试

SELECT products.*, product_info.* FROM products
INNER JOIN product_info ON product_info.product_id = products.id
INNER JOIN specials ON specials.product_d = products.id
WHERE product_info.language = 'en'
AND product_info.title like ?
AND specials.from_date < NOW()
AND specials.to_date > NOW()
ORDER BY specials.product_id DESC, products.created_at DESC

但结果只是特殊产品..

3 个答案:

答案 0 :(得分:2)

如果不是每个产品都在特殊产品表中,您应该使用特殊产品进行LEFT JOIN,并将特价日期的验证放在ON CLAUSE中。然后你按products.id订购,但先把特价放在首位,然后用CASE WHEN:

进行验证
SELECT products.*, product_info.*
FROM products
INNER JOIN product_info ON product_info.product_id = products.id
LEFT JOIN specials ON specials.product_d = products.id
                  AND specials.from_date < NOW()
                  AND specials.to_date > NOW()
WHERE product_info.LANGUAGE = 'en'
  AND product_info.title LIKE ?
ORDER BY CASE 
    WHEN specials.product_id IS NOT NULL THEN 2
    ELSE 1
    END DESC,
  products.id DESC,
  products.created_at DESC

答案 1 :(得分:0)

试试这个

SELECT products.*, product_info.* FROM products
INNER JOIN product_info ON product_info.product_id = products.id
INNER JOIN specials ON specials.product_d = products.id
WHERE product_info.language = 'en'
AND product_info.title like ?
AND specials.from_date < NOW()
AND specials.to_date > NOW()
ORDER BY specials.product_id DESC,products.id DESC, products.created_at DESC

答案 2 :(得分:0)

SELECT 
   products.*, 
   product_info.*
FROM products
JOIN product_info ON product_info.product_id = products.id
LEFT JOIN specials 
   ON specials.product_d = products.id AND NOW() BETWEEN specials.from_date AND specials.to_date
WHERE product_info.LANGUAGE = 'en'
  AND product_info.title LIKE ?
ORDER BY 
   specials.product_id DESC NULLS LAST,
   products.product_id DESC,
   products.created_at DESC;

由于您没有所有产品的特价,您必须进行外部连接而不是内部连接。