简体   繁体   中英

SELECT data from many-to-many table

I'm trying to get data from a many-to-many table, but the query that I try to do that doesn't work

USERS TABLE
+-----------+
| ID | NAME |
+-----------+
|  1 | dani |
+-----------+
|  2 | john |
+-----------+

TASKS TABLE
+------------+
| ID | NAME  |
+------------+
|  1 | learn |
+------------+
|  2 | play  |
+------------+
|  3 | eat   |
+------------+

USERS-TASK TABLE (MANY-TO-MANY)
+--------------------+
| USER_ID | TASK_ID  |
+--------------------+
|  1      | 1        |
+--------------------+
|  1      | 2        |
+--------------------+
|  2      | 1        |
+--------------------+

I'm trying to get the tasks for USER_ID 2 which is 1 record, or USER_ID 1 which is 2 records by supplying the ID, but the query doesn't work...

SELECT TASKS.name
FROM
    USERS,
    TASKS,
    user_task
INNER JOIN
    USERS
  ON user_task.UserId = USERS.id
INNER JOIN
    TASKS 
  ON user_task.TaskId = TASKS.id
   WHERE USERS.id = 1;

Hope you can help me with that.

Try the below - you've mixed JOIN

SELECT TASKS.name
FROM user_task
INNER JOIN
    USERS
  ON user_task.UserId = USERS.id
INNER JOIN
    TASKS 
  ON user_task.TaskId = TASKS.id
   WHERE USERS.id = 1

Your join in incorrect, try the following.

SELECT 
    t.name
FROM user_task ut 
INNER JOIN USERS u
  ON ut.UserId = u.id
INNER JOIN TASKS t
  ON ut.TaskId = t.id
WHERE USERS.id = 1;

If you have an table who store you link between you 2 table, why you dont do that:

SELECT TASKS.name
FROM
TASKS
INNER JOIN USERS-TASK ON TASKS.ID = USERS-TASK.TASK_ID
WHERE
USERS-TASK.USER_ID = 1

Your join are wrong, you made multi from:

 USERS,
TASKS,
user_task

And after you made your join:

    INNER JOIN
    USERS
  ON user_task.UserId = USERS.id
    INNER JOIN
    TASKS 
  ON user_task.TaskId = TASKS.id

Just remove your useless "from" and it will be ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM