由OR运算符分隔的多个WHERE条件

时间:2018-03-13 09:58:00

标签: mysql sql

有人可以告诉我为什么这个查询无效。

SELECT msg.message, 
       users.fname, 
       users.id 
FROM   msg 
WHERE  ( 
              msg.f_init_id='1' 
       AND    msg.f_recv_id='2') 
OR     ( 
              msg.f_init_id='2' 
       AND    msg.f_recv_id='1') 
JOIN   msg.f_init_id=users.id 

这是我得到的错误:

Static analysis:

1 errors were found during analysis.

An alias was previously found. (near "ID" at position 199)

SQL query: Documentation

SELECT `msg`.`message`,`Users`.`fname`,`Users`.`ID` FROM `msg` WHERE (`msg`.`f_init_id`='1' AND `msg`.`f_recv_id`='2') OR (`msg`.`f_init_id`='2' AND `msg`.`f_recv_id`='1') JOIN msg.f_init_id=Users.ID LIMIT 0, 25

MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'JOIN msg.f_init_id=Users.ID LIMIT 0, 25' at line 1

4 个答案:

答案 0 :(得分:1)

通过将查询更改为:

来检查执行情况
SELECT `msg`.`message`,`Users`.`fname`,`Users`.`ID` 
FROM `msg` JOIN `Users` ON (Users.ID = msg.f_init_id) 
WHERE (`msg`.`f_init_id`='1' AND `msg`.`f_recv_id`='2') 
OR (`msg`.`f_init_id`='2' AND `msg`.`f_recv_id`='1') 
LIMIT 0, 25

JOIN子句用于组合两个或多个表中的行,基于它们之间的相关列。

WHERE子句出现在JOIN之后。 ON子句用于指定JOIN

的条件

答案 1 :(得分:1)

您应该在JOIN条件子句之前指定表之间的WHERE条件。为了简化代码,我删除了backtick

SELECT
    m.message,
    u.fname,
    u.ID
FROM 
    msg m
    JOIN Users u
        ON m.f_init_id = u.ID
WHERE
    (m.f_init_id = '1' AND m.f_recv_id = '2') 
    OR (m.f_init_id = '2' AND m.f_recv_id = '1')

希望这有帮助!

答案 2 :(得分:1)

您可以使用别名整理SQL语句,并删除额外的反引号:

SELECT a.message, b.fname, b.ID FROM msg a
JOIN Users b ON a.f_init_id = b.ID
WHERE (a.f_init_id = 1 AND a.f_recv_id = 2) 
OR (msg.f_init_id = 2 AND a.f_recv_id = 1) 
LIMIT 0, 25

由于f_init_id表格中的f_recv_idmsg数据类型为INT(或其他数字类型),因此值不需要包围单引号。

答案 3 :(得分:0)

您的JOIN语法有问题。你可以这样做,或者@sinto已经回答了。

SELECT `msg`.`message`,`Users`.`fname`,`Users`.`ID`
    FROM `msg`, `Users`
    WHERE msg.f_init_id=Users.ID  AND
        ((`msg`.`f_init_id`='1' AND `msg`.`f_recv_id`='2') OR (`msg`.`f_init_id`='2' AND `msg`.`f_recv_id`='1')) AND LIMIT 0, 25

由于它是一个JOIN,我更喜欢经典的JOIN语法(JOIN .... ON ...)