MySql where..in多列

时间:2018-02-18 17:49:10

标签: mysql sql

我需要在MySql中实现以下查询

SELECT name, value FROM opponent 
WHERE name in (SELECT name FROM noc WHERE fictive_status='fictional') 
AND value in (SELECT name FROM noc WHERE fictive_status='fictional')

我需要找到表中对手的所有行(名称,值(某些其他名称)),其中另一个表noc中的fictive_status(两者)是虚构的'。

尝试

SELECT name, value from opponent WHERE(name,value) in (SELECT name FROM noc WHERE fictive_status='fictional')

需要2列操作数和

Select name, value from opponent where (name and value) in (select name from noc where fictive_status='fictional')

返回对手表中的所有行。

如何以更好的方式实施?

3 个答案:

答案 0 :(得分:2)

像你这样使用两个子查询是低效的,因为MySQL必须为每个子查询生成一个大的临时表,从noc存储 ever 名称。这是一个很大的临时表。

相反,我建议您使用JOIN

SELECT DISTINCT o.name, o.value 
FROM opponent AS o 
JOIN noc AS n1 ON n1.fictive_status='fictional' AND n1.name = o.name
JOIN noc AS n2 ON n2.fictive_status='fictional' AND n2.name = o.value

如果您在noc(fictive_status, name)上拥有正确的索引,那么这将不会很昂贵。它不会扫描整个表,它只会搜索匹配的行。

DISTINCT用于在noc中有多个匹配项的情况下减少结果集。

答案 1 :(得分:1)

请滚筒。 。 。您可以在MySQL中实现:

SELECT o.name, o.value
FROM opponent o
WHERE o.name in (SELECT noc.name FROM noc WHERE noc.fictive_status = 'fictional') and
      o.value in (SELECT noc.name FROM noc WHERE noc.fictive_status = 'fictional');

这实际上是您对列别名的查询。没有先验更改它的原因。该查询使用ANSI标准SQL,几乎可以在任何数据库中使用。

答案 2 :(得分:0)

您可以在EXISTS

中使用以下内容
 SELECT o.name, o.value 
    FROM opponent AS o 
    WHERE EXISTS
    (
      SELECT * FROM noc As n1 WHERE n1.name = o.name  AND n1.fictive_status='fictional'
    )
    AND EXISTS
    (
       SELECT * FROM noc As n1 WHERE n1.name = o.value   AND n1.fictive_status='fictional'
    )