简体   繁体   English

内部联接以接收多个值

[英]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. 假设我有表“ apple”和“ orange”,我希望能够内部连接这些表,在这些表中我提供“ num”并接收任务名称,以换取所有4个任务。

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. 给定我说的num = 1,这将提供Task1的名称。

Is there a way to receive the name for Task1, Task2, Task3, Task4, given I say num = 1? 给定num = 1,有没有办法接收Task1,Task2,Task3,Task4的名称? Or do I need to have 4 separate request? 还是我需要有4个单独的请求?

这是桌子

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. 上面的查询将仅返回具有至少1个Task的行(假定它位于apple.Task1中)。 If you're always guaranteed to have 4 tasks, you can use an INNER JOIN for each JOIN to narrow results. 如果始终保证有4个任务,则可以对每个JOIN使用INNER JOIN JOIN来缩小结果。 Otherwise, a LEFT OUTER JOIN won't eliminate rows that have a NULL task. 否则, LEFT OUTER JOIN不会消除具有NULL任务的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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