MySQL从三个表中获取信息

时间:2013-09-07 10:48:06

标签: mysql

我是SQL新手所以请耐心等待。我正在写一个loginscript,想从三个表中获取信息。问题是此查询仅从table3返回一个值。有人可以给我一些指示。

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)

谢谢。

1 个答案:

答案 0 :(得分:1)

这是您的查询(格式化,以便我可以更好地阅读):

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;