使用mysql联接查询选择数据

时间:2018-10-05 14:22:02

标签: mysql

此查询有效。

TABLE用户

userid   firstname    lastname
1         JOHN         DEO
2         JANE         DEO

TABLE msg

msg_id    msg_from     msg_to      received   
1         userid(1)    userid(2)   null       


SELECT SND.userid, SND.firstname, SND.lastname
FROM msg as M
JOIN users as SND 
  ON SND.userid = M.msg_from
WHERE M.msg_to = 'userid -1'
  AND M.received IS NULL

但此查询无效

TABLE users

userid   firstname    lastname
1         JOHN         DEO
2         JANE         DEO

TABLE msg

msg_id    msg_from     msg_to      received   age  city  country
1         userid(1)    userid(2)   null       26   any   any


SELECT SND.userid, SND.firstname, SND.lastname, SND.age, SND.city, SND.country
FROM msg as M
JOIN users as SND 
  ON SND.userid = M.msg_from
WHERE M.msg_to = 'userid -1'
  AND M.received IS NULL

我想从味精表上的数据库中选择年龄城市国家,但看起来我的查询存在从味精表中选择年龄城市和国家的问题

2 个答案:

答案 0 :(得分:0)

您需要将SND.age,SND.city,SND.country更改为M.age,M.city,M.country,因为它们来自表msg

SELECT SND.userid, SND.firstname, SND.lastname, M.age, M.city, M.country
FROM msg as M
JOIN users as SND 
  ON SND.userid = M.msg_from
WHERE M.msg_to = 'userid -1'
  AND M.received IS NULL

答案 1 :(得分:0)

使用以下查询:

SELECT SND.userid, SND.firstname, SND.lastname, M.age, M.city, M.country
FROM msg as M
JOIN users as SND 
ON SND.userid = M.msg_from
WHERE M.msg_to = 'userid -1'
AND M.received IS NULL