web-dev-qa-db-ja.com

Mysqlサブクエリが複数の行を返す

SELECT * FROM wp_posts WHERE ID IN 
(
(SELECT courses  FROM wp_category WHERE CatID =401) OR 
(SELECT  meta_value FROM wp_postmeta WHERE  post_id IN (SELECT courses FROM wp_category WHERE CatID =401) AND meta_key ='post_id' )
) 
AND 
ID IN (SELECT post_id FROM wp_locations_courses WHERE location_id = 1120)

サブクエリでINを使用しているときに上記のクエリで問題が発生し、エラーSubquery returns more than 1 rowIN句を使用しているときに発生する理由

5
M Khalid Junaid
        (SELECT courses  FROM wp_category WHERE CatID =401) 
        OR 
        (SELECT  meta_value FROM wp_postmeta WHERE  post_id IN (SELECT courses FROM wp_category WHERE CatID =401) AND meta_key ='post_id' )

これは条件ですが、n値が必要です。

これはうまくいくはずです:

(
    ID IN 
        (
            (SELECT courses  FROM wp_category WHERE CatID =401) 
        )
    OR
    ID IN 
        (
            (SELECT  meta_value FROM wp_postmeta WHERE  post_id IN 
                (SELECT courses FROM wp_category WHERE CatID =401) AND meta_key ='post_id' )
        )
)

MySQLでのサブクエリにも注意してください。あなたの場合、サブサブクエリ。

ここを見てください: https://stackoverflow.com/questions/12356784/mysql-dependent-sub-query-with-not-in-in-the-where-clause-is-very-slow =

6
edze
SELECT * FROM wp_posts WHERE ID IN 
(
   (SELECT courses  FROM wp_category WHERE CatID =401) OR 
   (SELECT  meta_value FROM wp_postmeta WHERE  post_id IN (SELECT courses FROM wp_category WHERE CatID =401) AND meta_key ='post_id' )
) 
AND 
ID IN (SELECT post_id FROM wp_locations_courses WHERE location_id = 1120);

これらの厄介なサブクエリを書き直して、結果の結合パーティションに存在するかどうかを確認します。

SELECT * FROM wp_posts WHERE EXISTS ( 
    SELECT 1 FROM
       (
            SELECT courses, cat_ID FROM wp_category
                UNION  -- union for OR
            SELECT meta_value AS "courses", cat_ID 
                FROM wp_postmeta, wp_category 
                WHERE post_id=courses AND meta_key ='post_id' 
       ) A, wp_locations_courses -- join for AND
          WHERE 
             ( wp_posts.ID, 1120 ) IN ( post_id, location_id ) AND  -- resultant join #1
             ( wp_posts.ID, 401 ) IN ( courses, cat_ID )  -- resultant join #2
    );

このため、特に3つの参照テーブルにインデックスを付けてパーティション分割することは、特にそれぞれに多くのレコードを持つ多数の潜在的な異なるcat_IDがある場合に価値があります。

1
JJ Ward