2016-11-06 5 views
-2

私はusers_tableとordersのテーブルとcities_translationという都市名のテーブルを持っています。ユーザーテーブルには、ユーザーID、名字、姓、市区町村ID、代表IDがあります。代理人は、同じ表の別のユーザーです。MySQLの自己結合テーブルエラー#1066 - ユニークでないテーブル/エイリアス:cities_translation

Select 
    orders.id, orders.user_id, orders.total, orders.final_total, orders.order_status_id, 
    orders.unix_time, u.id,u.email, u.first_name, u.last_name,m.first_name as rep_firstname, 
    m.last_name as rep_lastname, u.representative_id,u.city_id,cities_translation.* 
From orders,cities_translation,users u 
    left join cities_translation 
Where u.city_id = cities_translation.city_id 
    And orders.user_id = u.id 
    And cities_translation.lang_id='2' 
    And orders.order_status_id='1' 
Left join users r on u.representative_id = r.id 
Group by orders.user_id 
Limit 5 

しかし、結果は次のとおりです:「#私がやりたいことは期待される結果が

user id first name last name order id city name representative 

    1   foo   bar   1   city1   user  

クエリでこの

user id first name last name city name representative wholesaler 

    1   foo   bar  city1   2    yes 
    2   user   user  city2   0    no 

のようなテーブルを取得するために、これらのテーブルを結合することです1066 - ユニークではないテーブル/エイリアス: 'cities_translation'このエラーを回避し、各卸売業者の代表的な名前を得るためにこのクエリを書き直すにはどうすればいいですか

+0

暗黙的および明示的な結合構文を使用しないでください!結合の正しい構文のみを使用すれば、この問題を回避するのに役立ちます。また、別名**の**テーブルごとに別名をつけると、この問題は発生しません。 – sagi

+0

私はどこにmを見ることができません。エイリアスはどこから来ていますか? –

答えて

2

あなたが明示的に混合され、implictが

From orders,cities_translation,users u 
left join cities_translation 

に参加して、あなたはフォーマットに参加し、適切な明示的なを採用すべきである。..

とにかくエラーメッセージがあなたが(2時間表cities_translationを使用することを10の事実に関連していますあなたは、この表2の時間が必要な場合は、テーブルの各単一istanceを参照し、関連するカラム名

のための接頭辞として正しいエイリアスを使用するために、あなたは適切な別名を使用する必要があります

)参加から、左に

1

エラーが示唆するように、2回結合されているテーブルの一意のエイリアスを作成する必要があります。

Select 
    orders.id, orders.user_id, orders.total, orders.final_total, orders.order_status_id, 
    orders.unix_time, u.id,u.email, u.first_name, u.last_name,m.first_name as rep_firstname, 
    m.last_name as rep_lastname, u.representative_id,u.city_id,cities_translation.* 
From orders,cities_translation ct1,users u 
    left join cities_translation ct2 
ON u.city_id = ct1.city_id /** you probably wanted ON here INSTEAD OF WHEN*/ 
    And orders.user_id = u.id 
    And ct2.lang_id='2' 
    And orders.order_status_id='1' 
Left join users r on u.representative_id = r.id 
Group by orders.user_id 
Limit 5 

適宜、ct1とct2を変更してください。

サイドノート: SQLの予約語は、大文字と小文字のカラムテーブル名で記述するのが通例です。
明示的および暗黙的な結合を混合しています。後でコードを読んでいるとき、それは常に混乱につながります。可能な限り明示的な結合を使用してみてください。
この形式のGROUP BYは、mysql 5.7+では動作しません

+0

ジョインとグループの間の集約がない場合のwhere節は問題ありませんか? –

+0

oops @ P.Salmon指摘してくれてありがとう!もちろん、別のエラー – e4c5

+0

エラーが発生します: "near 'where u.city_id = ct1.city_idそしてorders.user_id = u.idとct2.lang_id =' at line 7" –

関連する問題