2016-09-17 2 views
1

これらの製品の結果は、別のテーブルインデックスに存在するかどうかに基づいて取得されます。私はそれらが存在するすべてのインスタンスの数を取得しようとしているので、関連性によって結果を並べ替えることができます。私が試してみると、変数@priorityを0として返すようです。複数のEXIST()ステートメントを含むクエリを使用してインデックスが存在する回数をカウントします。

おそらく、結合ステートメントを使用する方が良いでしょうか?

ありがとうございました。私のMySQLのクエリは次のとおりです:

SELECT `products` . * , @priority 
    FROM `products` 
    LEFT JOIN productstypes_index ON productstypes_index.product_id = products.id 
WHERE (

EXISTS (

SELECT * 
    FROM `productstypes_index` 
    WHERE `productstypes_index`.`product_id` = `products`.`id` 
    AND `productstypes_index`.`_type_id` = '1' 
) 
AND (
(
(

EXISTS (

SELECT @priority := COUNT(*) 
    FROM `producthashtags_index` 
    WHERE `producthashtags_index`.`product_id` = `products`.`id` 
    AND `producthashtags_index`.`producthashtag_id` = '43' 
) 
) 
AND (

EXISTS (

SELECT @priority := COUNT(*) 
    FROM `producthashtags_index` 
    WHERE `producthashtags_index`.`product_id` = `products`.`id` 
    AND `producthashtags_index`.`producthashtag_id` = '11' 
) 
) 
) 
) 
) 
ORDER BY `updated_at` DESC; 
+0

MySQLはEXISTSサブクエリのSELECTリストを無視するので、そこに入力したものと違いはありません。 –

答えて

0

existsなしで、変数を使用せずに行うことができます。また、exists条件が結合テーブルにある場合、left joinには意味がありません。次に、より効率的なinner joinを実行し、余分なタイプの条件を結合条件に入れます。

優先度は、ハッシュタグのカウントで計算できますが、id in ('43', '11')のもののみで計算できます。

SELECT  products.* 
      count(distinct producthashtags_index.producthashtag_id) priority 
FROM  products 
INNER JOIN productstypes_index 
     ON productstypes_index.product_id = products.id 
     AND productstypes_index._type_id = '1' 
INNER JOIN producthashtags_index 
     ON producthashtags_index.product_id = products.id 
     AND producthashtags_index.producthashtag_id in ('43', '11') 
GROUP BY products.id 
ORDER BY updated_at DESC; 
+0

あなたは何かをしていると思いますが、私のインデックステーブルのproducthashtags_indexにはidがありません。 –

+0

ちょっとトリコット、ここでproducthashtag_indexに参加する必要はありませんか? エラーが発生します: 'フィールドリスト'に 'producthashtags_index.producthashtag_id'という列がありません –

+0

はい、あります。私はそれを更新してみましょう... – trincot

0

MySQLはEXISTSサブクエリのSELECTリストを無視するので、そこに入力する内容に違いはありません。これは文書番号hereです。

使用してのアプローチは以下のようになります加わり:

SELECT p.id, 
     COUNT(case when phi.product_id is not null then 1 end) AS instances 
FROM products p 
INNER JOIN productstypes_index pti ON pti.product_id = p.id AND pti.`_type_id` = 1 
LEFT JOIN producthashtags_index phi ON phi.product_id = p.id AND phi.producthashtag_id IN (11,43) 
GROUP BY p.id 
ORDER BY instances DESC; 

私は、彼らが必要ありませんであり、また、テーブルであなたのid列が整数である場合、あなたが引用符を必要としないと信じて、追加のバッククォートを削除しました。

+0

@RickJamesあなたの編集に感謝します。ペーストエイリアスをコピーしてください:) –

+0

他の解決策として、私は私のインデックステーブルに一意のIDが必要だと思います。 –

+0

@KevinJ答えを編集しました。これを試してみてください。 –

関連する問題