我正在PHP中运行此SQL LEFT JOIN查询,但它显示了一个重要列,即 user_id
为null,即非null 。
MYSQL查询
SELECT
a.*,
b.*,
c.*,
d.*
FROM ts_users_skills a
LEFT JOIN ts_students_log b
ON a.`user_id` = b.`user_id`
LEFT JOIN ts_students_info c
ON a.`user_id` = c.`user_id`
LEFT JOIN `geo_records` d
ON a.`user_id` = d.`user_id`
WHERE (a.`skillsTeach` = '$skill_1' OR a.`skillsTeach` = '$skill_2'
OR a.`skillsTeach` = '$skill_3')
GROUP BY a.`user_id`;
JSON输出
{
"status": "success",
"nearby_teachers": [
{
"user_id": null,
"skillsTeach": "PHP",
"email": "praveenkumarkp666@gmail.com",
"country_code": "91",
"username": "praveenkum",
"name": "Procusa Founder",
"gender": "M",
"birthday": "1997-02-25",
"location": "Bhubaneswar"
},
{
"user_id": null,
"skillsTeach": "marketing",
"email": "ashok@procusa.in",
"country_code": "91",
"username": "ashok",
"name": "Ashok the founder 2",
"birthday": "1993-11-18",
"location": "Bhubaneswar"
},
{
"user_id": null,
"skillsTeach": "html",
"email": "talspo@gmail.com",
"country_code": "91",
"username": "talspo",
"name": "Procusa Founder",
"gender": "M",
"birthday": "1997-01-01",
"location": "Bhubaneswar"
}
]
}
谢谢。
答案 0 :(得分:1)
您的代码存在的问题是它返回了几列名为user_id的列。来自LEFT JOIN
的某些值可能会以NULL
的形式出现。
当序列化为键唯一的JSON时,很可能已选择«错误»字段,从而产生了NULL
值。
要解决此问题,您想精确列出要从每个表中检索的字段,而不要使用*
。当然,user_id
应该来自未经LEFT JOIN
编辑的表:
SELECT
a.user_id, a.field1, a.field2
b.field11, b.field12
c.field21, c.field22, c.field23
d.field31
...
详细信息
您正在使用*
选择字段:
SELECT
a.*,
b.*,
c.*,
d.*
...
但是您的查询显示您有多个名为user_id
的字段:
...
LEFT JOIN ts_students_log b
ON a.`user_id` = b.`user_id`
LEFT JOIN ts_students_info c
ON a.`user_id` = c.`user_id`
LEFT JOIN `geo_records` d
ON a.`user_id` = d.`user_id`
...
答案 1 :(得分:-1)
您在不同的表中有几列user_id
。
在您的JSON中,只有一个user_id
字段,不清楚从哪个表开始。
很明显,此时数据正在丢失,JSON包含来自数据集中的user_id
字段,而没有填充user_id
字段。
尝试使用与user_id
不同的表中的ts_users_skills a
。