2

我正在尝试在下面运行脚本,但总是为 name 字段获取 NULL 值。

SELECT u.name AS _user_name, s.name AS _school_name
FROM fwg_files AS f
LEFT JOIN users AS u ON u.id = f.user_id
LEFT JOIN user_profiles AS up ON up.user_id = u.id
LEFT JOIN school AS s ON s.id = up.profile_value

在我看来,这个问题在 JOIN ON school 表中,我尝试 SELECT s.id 并且它也返回 NULL 值。当我将最后一行更改为 RIGHT JOIN 时,它开始工作,但我只能看到 s.name 值,其他为 NULL

表 fwg_files

id  | user_id
240 | 414
241 | 436

表用户

id  | name
414 | Name 1
436 | Name 2

表 user_profiles

user_id | profile_value
414     | "6"
436     | "14"

表学校

id | name

 6 | School 1
14 | School 2

谢谢

4

1 回答 1

2

如果profile_value列上的引号是必须的,则需要使用 mix ofCONVERTSUBSTRING_INDEX去掉引号才能进行操作。

检查以下代码:

SELECT users.name as User, s.name as School
  FROM fwg_files AS ff
  LEFT JOIN users ON users.id = ff.user_id
  LEFT JOIN user_profiles AS up ON up.user_id = users.id
  LEFT JOIN school AS s ON s.id = CONVERT(SUBSTRING_INDEX(up.profile_value,'"',-2),UNSIGNED INTEGER);

这里是带引号的工作 SQL Fiddle 代码。

于 2013-02-26T13:41:24.863 回答