1

words我在和之间有多对多的关联definitions

words:
+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | int(11)      | NO   | PRI | NULL    | auto_increment |
+-----------------+--------------+------+-----+---------+----------------+

definitions:
+-------------------+--------------+------+-----+---------+----------------+
| Field             | Type         | Null | Key | Default | Extra          |
+-------------------+--------------+------+-----+---------+----------------+
| id                | int(11)      | NO   | PRI | NULL    | auto_increment |
| language_id       | int(11)      | YES  | MUL | NULL    |                |
+-------------------+--------------+------+-----+---------+----------------+

definitions_words:
+---------------+---------+------+-----+---------+-------+
| Field         | Type    | Null | Key | Default | Extra |
+---------------+---------+------+-----+---------+-------+
| definition_id | int(11) | NO   | PRI | NULL    |       |
| word_id       | int(11) | NO   | PRI | NULL    |       |
+---------------+---------+------+-----+---------+-------+

我想获得所有与 . 定义完全相同的单词记录language_id = 1

4

2 回答 2

2

我认为用 SQL 表达这一点的最简单方法是使用in

select *
from words
where id in (select word_id
             from word_definitions
             where language_id = 1
             having count(*) = 1
            )

但是,in子查询在 MySQL 中并不总是有效地工作。它可以用一个exists子句代替:

select *
from words w
where exists (select 1
              from word_definitions wd
              where language_id = 1
              having count(*) = 1 and wd.word_id = w.id
             )
于 2013-01-24T11:41:32.143 回答
1
SELECT  a.ID, COUNT(*) totalRecordCount
FROM    words a
        INNER JOIN definition_words b
            ON a.ID = b.word_ID
        INNER JOIN definitions c
            ON b.definition_id = c.ID
        INNER JOIN
        (
            SELECT  id,
                    SUM(language = 1) totalCount
            FROM    definitions
            GROUP   BY id
        ) d ON c.ID = d.ID AND 
               d.TotalCount = 1
GROUP   BY a.ID
于 2013-01-24T11:37:33.763 回答