MySQL查询以获取第一个位置上的特定ID

时间:2018-11-24 06:58:28

标签: mysql

127.0.0.1:8000/store/1

响应为:

    SELECT `p`.`cat_pid`, `p`.`cat_id`, `c`.`name`, substring_index(group_concat(p.image_1 SEPARATOR ', '), ', ', 3) as images
FROM `products` `p`
LEFT JOIN `categories` `c` ON `p`.`cat_id` = `c`.`id`
WHERE `p`.`admin_response` = 1
AND `p`.`isactive` = 1
GROUP BY `p`.`cat_id`
ORDER BY `p`.`cat_id` ASC, `p`.`created_date` ASC

现在我希望第一个位置上的cat_id 71其余数据应该保持不变。

1 个答案:

答案 0 :(得分:2)

您可以通过field()使用订单

SELECT `p`.`cat_pid`
    , `p`.`cat_id`
    , `c`.`name`
    , substring_index(group_concat(p.image_1 SEPARATOR ', '), ', ', 3) as images
FROM `products` `p`
LEFT JOIN `categories` `c` ON `p`.`cat_id` = `c`.`id`
WHERE `p`.`admin_response` = 1
AND `p`.`isactive` = 1
GROUP BY `p`.`cat_id`
ORDER BY field(`p`.`cat_pid`, 71) DESC, `p`.`cat_pid` ASC, `p`.`created_date` ASC