我在MySQL中有以下表格:
用户
轮廓
费率
在用户表中,我有以下记录:

id: 1
name: John
status: active

In profile, I have the following:

id: 5
bio: blah blah blah
user_id: 1

The table rates is empty, but contains the following fields:

id, rate, and user_id

I am trying to use SQL to query these tables and display information about the user, their user profile (if they have one), and their rates (if one exists). The SQL I am using is as follows:

SELECT user.name, profile.bio, rate.rate
FROM user
LEFT JOIN (profile, rate) ON (user.id = profile.user_id AND user.id = rate.user_id)
WHERE status = 'active';

这里的问题是,上面的sql返回user.name数据,但是profile.bio为空,即使profile表中有匹配的用户id记录。如果rates表中没有与该用户匹配的记录,MySQL似乎不会显示bio数据。
如果我想让SQL显示用户的名字以及他们的生物和小时率(如果存在的话),我会怎么做呢?我有点困惑,因为我认为上面的SQL应该可以工作。
谢谢!

最佳答案

SELECT user.name, profile.bio, rate.rate
FROM user
LEFT JOIN profile ON user.id = profile.user_id
LEFT JOIN rate ON user.id = rate.user_id
WHERE status = 'active'

您试图合并左连接逻辑,但只有当两个条件都为真时,它才会连接(user.id = profile.user_id AND user.id = rate.user_id)。

10-06 13:08
查看更多