1

ユーザーのリストを実行し、連絡先の項目の種類ごとにグループ化された、各ユーザーが行った連絡先のリストを 1 つのフィールドに抽出したいと考えています。このようなもの:

user_id, user_name, user_contact_views
100, john, 'a=21,b=22,c=3'
101, mary, 'a=53'
102, jack, 'b=13,c=5'

このクエリはほとんど機能しています

SELECT
u.id user_id,
u.name user_name,
(select group_concat(type_id_n_contacts)
 from (select CONCAT(item_type_id, '=', count(*)) type_id_n_contacts
        from item_contact ic
        where ic.user_id = u.id
        group by item_type_id) sq_type_id_n_contacts
) as user_contact_views
, ... -- Lots of fields
FROM user u
INNER JOIN -- Other tables, field, where and so on ignored
WHERE ...
ORDER BY ...
LIMIT ...;

しかし、私は得る

Error Code: 1054. Unknown column 'u.id' in 'where clause'

ネストされたクエリから u.id を使用することはできません。それを解決するための回避策を知っていれば幸いです。MySQL 変数はどうですか? u.id の値をサブサブクエリの変数に取得して、ic.user_id = @user_id を使用するにはどうすればよいですか?

重要な注意:フィールド セクションでサブクエリを使用する必要があります。カウント文字列に関連する事前計算されたすべての users_id を使用して JOIN で一時テーブルを作成することにより、クエリを機能させることができます (Giulio の回答を参照)。私はそれを知っていますが、フィールドが多すぎて、ユーザーのテーブル全体でそれを行い、後でインデックスを付けずに結合を作成できます。そのため、クエリ実行の最後のフェーズで、MySQL に、WHERE と LIMIT によって既にフィルタリングおよび制限されている user_ids のみを使用してサブクエリを実行するようにします。私は自分自身を説明したことを願っています。

ありがとう!

4

1 に答える 1

0

結合部分でサブクエリを移動してみてください。

    SELECT
    u.id,
    u.name,
     table_tmp.user_cont as user_contact_views,
    , ... -- Lots of fields
    FROM user u
    INNER JOIN
     (select group_concat(type_id_n_contacts) as user_cont, sub_user_id
     from (select CONCAT(item_type_id, '=', count(*)) type_id_n_contacts, ic.user_id as sub_user_id
            from item_contact ic
            group by item_type_id) sq_type_id_n_contacts
    ) as table_tmp ON table_tmp.sub_user_id = u.id
    INNER JOIN -- Other tables, field, where and so on ignored
    WHERE ...
    GROUP BY ...
    ORDER BY ...;
于 2014-07-04T12:26:44.027 に答える