1

私はSQLが初めてなので、ご容赦ください。
ログインスクリプトを書いていて、3 つのテーブルから情報を取得したいと考えています。問題は、このクエリが table3 から 1 つの値しか返さないことです。
誰かが私にいくつかの指針を教えてください。

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) です。

ありがとうございました。

4

1 に答える 1

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 ;

1 つの問題は、の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');

ただし、それが1行の問題を引き起こしているとは思いません。どちらかといえば、それは行数を増やします。

すべての値を 1 つの行で取得したいように思われますが、クエリは の各行に対して個別の行を返します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;
于 2013-09-07T14:41:40.727 に答える