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当我想测试是否缺少某些数据时,我通常使用 an 。当未找到匹配项时,t5将为 NULL。

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 回答