我有一个带有两个参数的MySQL,$ catname和$ limit = 1。 它工作正常。
SELECT P.*, C.Name AS CatName
FROM omc_product AS P
LEFT JOIN omc_category AS C
ON C.id = P.category_id
WHERE C.Name = '$catname'
AND p.status = 'active'
ORDER BY RAND()
LIMIT 0, $limit
现在我想添加另一个参数$ order。 $ order可以是
ODER BY RAND()
或
ORDER BY product_order
表omc_product。
有人能告诉我如何写这个查询吗?
提前致谢。
答案 0 :(得分:1)
从评论到this MySQL 5.0参考文章:
您可以使用ORDER BY
语句的CASE
子句中的ORDER BY
表达式SELECT
动态column_name参数:
CREATE PROCEDURE `orderby`(IN _orderby VARCHAR(50))
BEGIN
SELECT id, first_name, last_name, birthday
FROM table
ORDER BY
-- numeric columns
CASE _orderby WHEN 'id' THEN id END ASC,
CASE _orderby WHEN 'desc_ id' THEN id END DESC,
-- string columns
CASE _orderby WHEN 'first_name' THEN first_name WHEN 'last_name' THEN last_name END ASC,
CASE _orderby WHEN 'desc_first_name' THEN first_name WHEN 'desc_last_name' THEN last_name END DESC,
-- datetime columns
CASE _orderby WHEN 'birthday' THEN birthday END ASC,
CASE _orderby WHEN 'desc_ birthday' THEN birthday END DESC;
END