限制mysql关系表

时间:2017-08-22 23:29:05

标签: mysql

我有以下表格:

表:单词 - 超过200,000行

id word
1  a
2  b
3  c
4  d
and so on.

表:pos

id part
1  noun
2  verb
3  adjective
4  adverb
and so on.

定义 - 超过500,000行

id wordid posid definition
1  1      1     The first letter of the Roman alphabet.
2  1      1     Blood group 'A'.
3  1      1     The abbreviation of Ace.
4  2      1     The second letter of the Roman alphabet.
5  2      1     The definitions of B go on.

我希望最快的查询来限制单词而不是定义。非常感谢您的帮助。

我试过了:

SELECT word, part, definition 
FROM words, pos, definitions
WHERE words.id = wordid
AND pos.id = posid
ORDER BY word
LIMIT 2

2 个答案:

答案 0 :(得分:0)

您需要使用此查询更快地检索数据:

SELECT w.word,p.part,d.definition
from  definitions d 
inner join pos p
on d.posid=p.id
inner join words w
on w.id=d.wordid
order by word

我的代码与您的代码之间存在差异:

一个区别是第一个选项通过在where子句中表达连接条件来隐藏意图。

读取连接条件的第二个选项对于读取查询的用户更清楚。它显示了查询的确切意图。

内部联接语法更受欢迎,因为它更易于读者阅读,因为其他人已经评论过,有时候更快,就像数据一样

就表现或任何其他差异而言,不应该有任何。两个查询都应返回完全相同的结果,并在大多数RDBMS下执行相同的操作。

编辑:

最终守则是:

SELECT w.word,p.part,d.definition
from  definitions d 
inner join pos p
on d.posid=p.id
inner join words w
on w.id=d.wordid
order by word
WHERE 
(SELECT COUNT(*)
 FROM words w 
 WHERE w.id = d.wordid ) <=2

我希望此代码能为您提供帮助。

答案 1 :(得分:0)

感谢大家的帮助和时间。我在另一个链接和@B上发布了这个问题。德赛回答得对。这是我要查询的问题:

SELECT w.word,d.definition,d.pos FROM 
  (SELECT id, word FROM words ORDER BY id LIMIT 5) w 
  JOIN definition  d ON d.wordid = w.id

这里是链接:How to limit words but not definitions using mysql