SQL格式难度

时间:2014-10-28 18:58:07

标签: php mysql sql

我对SQL语句有疑问。我有以下声明:

SELECT id, user_id, receiver AS friend 
FROM messages 
WHERE user_id = %d || receiver = %d

在同一个表(消息)中还有两个字段:

  1. Storage_A

  2. Storage_B

  3. 现在我想用这个SQL做点别的事情:

    我只想选择Storage_A != 0 when user_id = %d

    的行

    我只想选择Storage_B != 0 when receiver = %d

    的行

4 个答案:

答案 0 :(得分:2)

使用AND条件添加额外检查,如下所示

SELECT id, user_id, receiver AS friend 
FROM messages 
WHERE (Storage_A != 0 and user_id = %d)
AND (Storage_B != 0 and receiver = %d)

即使您说过,您希望两个条件匹配,但我认为您希望在它们之间进行OR。所以WHERE条件是

where (Storage_A <> 0 and user_id = 8)

OR

(Storage_B <> 0 and receiver = 9)  

答案 1 :(得分:0)

使用括号对子句进行分组。

SELECT
    id, user_id, receiver AS friend
FROM
    messages
WHERE
    (user_id = %d && Storage_A != 0)
    OR (receiver = %d && Storage_B != 0)

答案 2 :(得分:0)

根据索引的设置方式,您可能需要执行两次查询并UNION

SELECT id, user_id, receiver AS friend 
  FROM messages 
  WHERE Storage_A != 0 AND user_id = %d
UNION
SELECT id, user_id, receiver AS friend 
  FROM messages 
  WHERE Storage_B != 0 AND receiver = %d

答案 3 :(得分:0)

试试这个

  SELECT id, user_id, receiver AS friend FROM messages WHERE (Storage_A != 0 and user_id = %d) and (Storage_B != 0 and receiver = %d)