Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
复杂mysql选择查询7_Mysql - Fatal编程技术网

复杂mysql选择查询7

复杂mysql选择查询7,mysql,Mysql,例如,我有表和值: CREATE TABLE IF NOT EXISTS `words` ( `wd_id` int(11) NOT NULL, `st_id` int(11) NOT NULL, ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ---------------------------- | wd_id | st_id | ---------------------------- | 2 |

例如,我有表和值:

CREATE TABLE IF NOT EXISTS `words` (
  `wd_id` int(11) NOT NULL,
  `st_id` int(11) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

----------------------------
|    wd_id    |    st_id    |
----------------------------
|      2      |     4       |
----------------------------
|      5      |     4       |
----------------------------
|      7      |     8       |
----------------------------
|      2      |     8       |
----------------------------
|      7      |     9       |
----------------------------
|      2      |     10      |
----------------------------
|      5      |     10      |
----------------------------
wd_id是单词的id
st_id是句子的id

如果我知道两个单词的id。我想得到包含这些单词的句子列表。 例如,这个ID是2和5,那么答案将是4和10

此表中将有数百万行。所以我需要认真写查询

以下是我写的问题:

  SELECT st_id 
  FROM words
  WHERE wd_id = 5 AND st_id IN (
      SELECT st_id
      FROM words
      WHERE wd_id = 2
    ) 
有人能写出更好的查询吗?或者查询哪一个对N个单词有效
如果我为wd_id和st_id列添加索引,则此查询将更快是吗?
什么类型的索引比较好?

SELECT  st_id
FROM    words
WHERE   wd_ID IN (2, 5)
GROUP   BY st_id
HAVING  COUNT(DISTINCT wd_ID) = 2
如果每个
st\u ID
wd\u ID
都是唯一的,那么having子句中不需要有
DISTINCT

HAVING  COUNT(*) = 2
您可以在这个链接上阅读更多内容


是的,您应该在“WHERE”条件下使用的任何字段中添加索引。在数据集开始增长之前,您不会注意到速度的提高,因为在记录数较少的情况下进行完整表扫描的成本较低。谢谢!在这一部分中,你能解释一下COUNT(DISTINCT wd_ID)=2以及如何查询N个单词吗?查询将过滤所有
st_ID
,其中
5
2
值为
wd_ID
。然后它对
st\u id
进行分组,并仅过滤值为
2
的记录,这是聚集行的结果,因为您正在
st\u id
中搜索两个值。那么N个单词呢?你能给我个主意吗?