我是新来的,所以请容忍我。我正在写一个登录脚本,想从三个表中获取信息。问题是此查询只返回表3中的一个值。有人能给我指点一下吗。
SELECT
table1.id,
table1.username,
table1.password,
table1.email,
table2.image,
table3.intValue,
table3.textValue,
table3.dateValue
FROM
table1
LEFT JOIN
table2
ON
table1.id = table2.userId
LEFT JOIN
table3
ON
table1.id = table3.userId
AND columnName='sex' OR columnName='birthdate' OR columnName='realname'
WHERE
table1.email = $username
OR
table1.username = $username
columnName='sex'是一个整数(intValue)
columnName='birthdate'是日期(dateValue)
columnName='realname'是字符串(textValue)
谢谢您。
最佳答案
这是您的查询(格式化以便我能更好地阅读):
SELECT t1.id, t1.username, t1.password, t1.email,
t2.image, t3.intValue, t3.textValue, t3.dateValue
FROM table1 t1 LEFT JOIN
table2 t2
ON t1.id = t1.userId LEFT JOIN
table3 t3
ON t1.id = t3.userId AND
columnName='sex' OR columnName='birthdate' OR columnName='realname'
WHERE t1.email = $username OR t1.username = $username ;
一个问题是
OR
上的table3
条件。评估结果如下: ON (t1.id = t3.userId AND columnName='sex') OR columnName='birthdate' OR columnName='realname';
SQL没有读心术。它调用优先规则。最好的情况是:
ON t1.id = t3.userId AND
columnName in ('sex', 'birthdate', 'realname');
不过,我不认为这会导致一排的问题。如果有的话,那将增加行数。
似乎您希望在一行中获得所有值,而查询将为
table3
中的每一行返回单独的行。如果是,则应使用group by
,并进行适当的聚合。最后一个问题是:SELECT t1.id, t1.username, t1.password, t1.email,
t2.image,
max(case when columnName = 'sex' then t3.intValue end) as sex,
max(case when columnName = 'realname' then t3.textValue end) as realname,
max(case when columnName = 'birthdate' then t3.dateValue end) as birthdate
FROM table1 t1 LEFT JOIN
table2 t2
ON t1.id = t1.userId LEFT JOIN
table3 t3
ON t1.id = t3.userId AND
columnName in ('sex', 'birthdate', 'realname')
WHERE t1.email = $username OR t1.username = $username
GROUP BY t1.id;
关于mysql - MySQL从三个表中获取信息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18672508/