MYSQL:
SELECT `item`.*
FROM `item`
LEFT JOIN `item_category`
ON `item_category`.`Item` = `item`.`id`
LEFT JOIN `item_sub_category`
ON `item_sub_category`.`Item` = `item`.`id`
LEFT JOIN `cart`
ON `cart`.`item` = `item`.`id`
AND `cart`.`user` = 3
LEFT JOIN `user_users`
ON `user_users`.`id` = 3
WHERE `cart`.`item` IS NULL
AND `item_sub_category`.`sub_category` IN( '65', '66', '67', '68' )
OR `item_category`.`category` IN( '35', '36' )
GROUP BY `item`.`id`
ORDER BY `item`.`id` DESC,
`item`.`feature` DESC
LIMIT 4
正如你所看到的那样,条件是OR。我想优先考虑两个条件都成立的行。我怎样才能达到这个结果?
答案 0 :(得分:0)
添加
, (CASE WHEN CONDITION1 AND CONDITION2 THEN 0 ELSE 1 END)
到你的ORDER BY子句,其中CONDITION1和CONDITION2是你的两个条件。
编辑显示在查询中并修复WHERE子句中的AND / OR问题
SELECT `item`.*
FROM `item`
LEFT JOIN `item_category`
ON `item_category`.`Item` = `item`.`id`
LEFT JOIN `item_sub_category`
ON `item_sub_category`.`Item` = `item`.`id`
LEFT JOIN `cart`
ON `cart`.`item` = `item`.`id`
AND `cart`.`user` = 3
LEFT JOIN `user_users`
ON `user_users`.`id` = 3
WHERE `cart`.`item` IS NULL
AND
(
`item_sub_category`.`sub_category` IN( '65', '66', '67', '68' )
OR
`item_category`.`category` IN( '35', '36' )
)
ORDER BY `item`.`id` DESC,
`item`.`feature` DESC,
CASE WHEN `item_sub_category`.`sub_category` IN( '65', '66', '67', '68' )
AND `item_category`.`category` IN( '35', '36' )
THEN 0
ELSE 1 END ASC
LIMIT 4
这样做是按虚拟列排序,当你想给它优先时它为0,而当你不给它时为1。