我有这个mysql设置:
*words* table
+----+-----------+
| id | word |
+----+-----------+
| 1 | curse1 |
| 2 | curse2 |
| 3 | niceWord1 |
*Category* table
+----+-----------+
| id | name |
+----+-----------+
| 1 | niceWords |
| 2 | badWords |
*link* table
+----+--------+-------+
| id | wordID | catID |
+----+-----------+----+
| 1 | 1 | 2 |
| 2 | 2 | 2 |
| 3 | 3 | 1 |
我想创建一个MySQL SELECT,我说我想用链接表选择所有坏词 所以我会得到类似这样的输出:
+----------+------------+---------------+
| words.id | words.word | Category.name |
+----------+------------+---------------+
| 1 | curse1 | badWords |
| 2 | curse2 | badWords |
我想我需要使用某种类型的JOIN,我不太擅长SQL。
使用相同的Pastebin:http://pastebin.com/ML684RRA
答案 0 :(得分:1)
select words.id, words.word, Category.name
from words
join link on link.wordid = words.id
join category on category.id = link.catid
where category.name = 'badWords'
答案 1 :(得分:1)
只需通过相关ID加入表格,然后通过使用WHERE坏词ID = 2来过滤掉好词...我还在表名中添加了别名,因为这是一个很好的做法。
SELECT
w.word,
c.name,
c.id
FROM words w
JOIN link l on l.wordID = w.id
JOIN Category c on c.id = l.catID
WHERE c.id = 2