简体   繁体   English

MYSQL从一个表查询SELECT并将结果与​​另一表联接

[英]MYSQL query SELECT from one table and join results with other table

I have two tables MESSAGES and USERS : 我有两个表MESSAGESUSERS

MESSAGES : MESSAGES

|id|user_id|message|1st number|2nd number|

USERS : USERS

|user_id|name|

I'm trying to display a message and by user_id get username next to the message. 我正在尝试显示一条消息,并通过user_id获取消息旁边的用户名。 Is it possible to do it in just one query? 只需一个查询就可以做到吗?

At this moment my demo query looks like that but it does not work. 目前,我的演示查询看起来像这样,但是它不起作用。

SELECT *
 FROM   messages
 WHERE  1st number BETWEEN $x AND $z
 AND 2nd BETWEEN $x AND $z
 LEFT JOIN users
 ON users.user_id= messages.user_id
 ORDER BY time DESC

The error which I get: You have an error in your SQL syntax; 我得到的错误:您的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LEFT JOIN users ON WHERE users.user_id= messages.user_id ORDER BY time DESC' at line 5 检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第5行的“在此处LEFT JOIN用户使用users.user_id = messages.user_id ORDER BY time DESC”附近使用

There are a few problems with your SQL: 您的SQL存在一些问题:

  • if a column name contains spaces, you need to quote them 如果列名包含空格,则需要用引号引起来
  • you need to write the full column names in mysql 您需要在mysql中编写完整的列名
  • JOIN comes before WHERE JOIN在WHERE之前出现

So something like 所以像

SELECT *
FROM messages
 LEFT JOIN users ON users.user_id=messages.user_id
WHERE `1st number` BETWEEN $x AND $z
 AND `2nd number` BETWEEN $x AND $z
ORDER BY time DESC

should work 应该管用

Please try this. 请尝试这个。

SELECT
    *
FROM
    messages
    LEFT JOIN users ON users.user_id = messages.user_id
WHERE
        `1st number` BETWEEN $x AND $z
    AND
        `2nd number` BETWEEN $x AND $z
ORDER BY time DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM