0

以下のようなクエリを使用すると、IDの色が青、紫、緑、白、黒の行をフェッチできます。

SELECT t1.id, col
FROM extra as e INNER JOIN your_table as t1 USING ( id )
CROSS JOIN your_table as t2 USING ( id )
CROSS JOIN your_table as t3 USING ( id )
CROSS JOIN your_table as t4 USING ( id )
CROSS JOIN your_table as t5 USING ( id )
WHERE t1.color = 'blue' and t2.color = 'purple' and t3.color= 'green' and t4.color= 'white' and t5.color= 'black'

!=またはNOT INを使用しようとすると、機能しないようです。色に青、紫、緑、白が含まれ、黒は含まれないようにクエリを作成するにはどうすればよいですか?

4

3 に答える 3

2

あなたは次の線に沿って何かをすることができます:

select e.id
from   extra as e
where  exists (select null from your_table as t where t.id = e.id and t.color = 'blue')
  and  exists (select null from your_table as t where t.id = e.id and t.color = 'purple')
  and  exists (select null from your_table as t where t.id = e.id and t.color = 'green')
  and  exists (select null from your_table as t where t.id = e.id and t.color = 'white')
  and not exists (select null from your_table as t where t.id = e.id and t.color = 'black')

または、このようなものの方がおそらくより効率的です。

select e.id
from   extra as e
where  4 = 
       (select count(*) 
        from   your_table as t 
        where  t.id = e.id 
          and  t.color in ('blue', 'purple', 'green', 'white'))
  and  0 = 
       (select count(*) 
        from   your_table as t 
        where  t.id = e.id 
          and  t.color in ('black'))
于 2009-10-25T03:14:05.160 に答える
2

なぜ使用しているのかわかりませんCROSS JOIN。これは通常、デカルト積を生成するためのものです。必要なのはプレーンINNER JOINまたは単純JOINです。

私は通常OUTER JOIN、いくつかのデータがないかどうかをテストしたいときにを使用します。一致するものが見つからない場合は、t5NULLになります。

SELECT t1.id, col
FROM extra as e 
INNER JOIN your_table as t1 ON ( e.id=t1.id AND t1.color = 'blue' )
INNER JOIN your_table as t2 ON ( e.id=t2.id AND t2.color = 'purple' )
INNER JOIN your_table as t3 ON ( e.id=t3.id AND t3.color = 'green' )
INNER JOIN your_table as t4 ON ( e.id=t4.id AND t4.color = 'white' )
LEFT OUTER JOIN your_table as t5 ON ( e.id=t5.id AND t5.color = 'black' )
WHERE t5.id IS NULL;

確かに、結合を使用する上記の手法は、相関サブクエリを使用するよりも高速であり、(少なくともMySQLでは)GROUP BY一部の人々が使用するソリューションよりも高速です。

SELECT e.id, col
FROM extra as e
INNER JOIN your_table AS t USING ( id)
WHERE t.color IN ('blue', 'purple', 'green', 'white')
GROUP BY e.id
HAVING COUNT(*) = 4;

(このクエリは「黒くない」問題を解決しません。私はテクニックを説明しているだけです。)

于 2009-10-25T04:06:03.260 に答える
0

クエリを複雑にしすぎていると思います。試行しているのは、このような標準の結合のようです。

select * from cars join colors where cars.colorid = colors.colorid where colors.color != 'black'
于 2009-10-25T03:23:57.400 に答える