如何使用2个值在2个表之间进行连接?

时间:2017-07-20 13:12:42

标签: mysql sql join mariadb

在Mariadb数据库中,我想进行查询以连接两个表:jokejokevote以获取由特定用户投票的所有笑话。

以下是表格:

笑话

+-------------+------------------+------+-----+-------------------+----------------+
| Field       | Type             | Null | Key | Default           | Extra          |
+-------------+------------------+------+-----+-------------------+----------------+
| id          | int(6) unsigned  | NO   | PRI | NULL              | auto_increment |
| title       | varchar(255)     | NO   |     | None              |                |
| content     | mediumtext       | NO   |     | NULL              |                |
| user_id     | int(10) unsigned | YES  |     | 0                 |                |
| username    | varchar(32)      | NO   |     | Unknown           |                |
...

jokevote:

+---------+------------+------+-----+---------+----------------+
| Field   | Type       | Null | Key | Default | Extra          |
+---------+------------+------+-----+---------+----------------+
| id      | int(11)    | NO   | PRI | NULL    | auto_increment |
| joke_id | int(11)    | NO   |     | NULL    |                |
| user_id | int(11)    | NO   |     | NULL    |                |
| vote    | tinyint(4) | NO   |     | NULL    |                |
+---------+------------+------+-----+---------+----------------+

jokevote的内容是: enter image description here

joke表中的一些值(与用户6相关): enter image description here

我尝试过的一个问题是:

    SELECT * FROM joke LEFT JOIN jokevote 
     ON joke.user_id=6  AND joke.id=jokevote.joke_id 
     AND jokevote.vote=1;

查询应该只返回2个笑话,但它会返回所有笑话。 我也尝试过这样的其他查询:

SELECT * FROM joke LEFT JOIN jokevote 
ON joke.user_id=6  AND joke.id=jokevote.joke_id AND 
jokevote.vote=1 AND joke.user_id=jokevote.user_id AND ;

(再次,返回所有的笑话)

所以我一直无能为力,想知道这种情况下的正确查询是什么?

1 个答案:

答案 0 :(得分:3)

我认为你打算用INNER JOIN来代替

SELECT * FROM joke INNER JOIN jokevote 
 ON joke.id=jokevote.joke_id 
 WHERE jokevote.vote=1
 AND joke.user_id=6;