我对IF ELSE语句在查询中的工作方式感到有些困惑。
这是我一直在尝试的,加上它的变化,但我似乎无法让它在没有错误的情况下恢复结果......
$get_trash = mysql_query("SELECT *
FROM message
WHERE message_to_user_id = '$user_id'
AND message_to_user_id_hide = 1
OR message_from_user_id = '$user_id'
AND message_from_user_id_hide = 1
IF message_to_user_id = '$user_id'
THEN ORDER BY message_to_user_id_hide_time DESC
ELSEIF
message_from_user_id = '$user_id'
THEN ORDER BY message_from_user_id_hide_time DESC
ENDIF") or die(mysql_error());
现在我已经无数次使用if else语句但是我从来没有在mysql查询中使用它,所以如果有人能说明你如何解决它,那么我真的很感激它!
答案 0 :(得分:4)
如果你能说出你的桌子是什么样的话会有所帮助。但是,基于您尝试过的SQL,我认为您正在寻找的是这样的:
SELECT * FROM message WHERE
(message_to_user_id = '$user_id' AND message_to_user_id_hide = 1) OR
(message_from_user_id = '$user_id' AND message_from_user_id_hide = 1)
ORDER BY
(CASE
WHEN message_to_user_id = '$user_id'
THEN message_to_user_id_hide_time
ELSE message_from_user_id_hide_time
END) DESC
答案 1 :(得分:2)
这可以满足您的需求吗?
ORDER BY CASE '$user_id' WHEN message_to_user_id
THEN message_to_user_id_hide_time
WHEN message_from_user_id
THEN message_from_user_id_hide_time END DESC