简体   繁体   中英

Inner join to receive multiple values

Lets say I have the tables "apple" and "orange", I wanted to be able to inner join these tables where I provide the "num" and receive the task name in return for all 4 task.

However it seems inner join would only work for one task, not all four.

SELECT orange.name
FROM apple
    INNER JOIN orange ON orange.task_id = apple.Task1
WHERE num = ? 

This will provide the name for Task1, given I say num = 1.

Is there a way to receive the name for Task1, Task2, Task3, Task4, given I say num = 1? Or do I need to have 4 separate request?

这是桌子

You can try by below code

select orange.name from 
    (select Task1 as task from apple t1
    union 
    select Task2 as task  from apple t1
    union
    select Task3 as task  from apple t1
    union
    select Task4  as from apple t1
    ) T inner join orange on orange.task_id=T.task
SELECT apple.num
  , o1.name AS task1
  , o2.name AS task2
  , o3.name AS task3
  , o4.name AS task4
FROM apple
INNER JOIN orange o1 ON o1.task_id = apple.Task1
LEFT OUTER JOIN orange o2 ON o2.task_id = apple.Task2
LEFT OUTER orange o3 ON o3.task_id = apple.Task3
LEFT OUTER orange o4 ON o4.task_id = apple.Task4
WHERE apple.num = ? 

The above query will return only the rows that have at least 1 Task, assuming it's in apple.Task1. If you're always guaranteed to have 4 tasks, you can use an INNER JOIN for each JOIN to narrow results. Otherwise, a LEFT OUTER JOIN won't eliminate rows that have a NULL task.

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