如何使用join但只获取第一个表的行?

时间:2016-05-17 22:03:28

标签: mysql sql join

我有这两个表:

// one
+----+-------+
| id | value |
+----+-------+
| 1  | aaa   |
| 2  | bbb   |
| 3  | ccc   |
+----+-------+

// two
+----+-------+
| id | value |
+----+-------+
| 2  | ddd   |
| 3  | eee   |
| 4  | fff   |
+----+-------+

这是我的疑问:

SELECT one.value FROM one JOIN two ON one.id = two.id

这是当前结果:

// 4 rows
+-----+
| bbb |
|     |
| ccc |
|     |
+-----+

这是预期输出:

// 2 rows
+-----+
| bbb |
| ccc |
+-----+

如您所见,我尝试one表中选择行。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

如果你在你的sql小提琴中尝试这个:

SELECT post_id, COUNT(*) from events
GROUP BY post_id
ORDER BY COUNT(*) DESC

您可以注意到每个qanda都有多个关联事件,因此您将获得所有匹配post_id的事件。

如果您期望两行,请添加DISTINCT

SELECT DISTINCT q.id, ee.table_code, q.subject 
FROM 
  qanda q JOIN 
  events ee on ee.post_id = q.id and 
         ee.author_id = 31 and 
         ee.table_code = 15

答案 1 :(得分:1)

这对你有用

SELECT table1.value FROM table1, table2 WHERE table1.id = table2.id 

这基本上是Equi join

您可以在此处详细了解Equi Join here