简体   繁体   English

从左表和全联接右表中选择值

[英]Select value from left table and full join right table

This is a bit difficult to explain, but I'll give my best: 这有点难以解释,但我会尽力而为:

Let's say, I have table A: 假设我有表A:

event | task | ref_person
------+------+-----------
  1   |  20  |     1
  2   |   9  |     2

And I have table B (containing person ): 我有表B(包含person ):

id | name
---+-----
 1 | foo
 2 | bar
 3 | jim

What does a MySQL-query look like, that produces this sort of table: 产生这种表的MySQL查询是什么样的:

 event | task | person
 ------+------+-------
   1   |  20  |   foo
   1   | NULL |   bar
   1   | NULL |   jim
   2   | NULL |   foo
   2   |   9  |   bar
   2   | NULL |   jim

My current approach is by using a RIGHT JOIN , but this won't get me the event combined with the NULL-value. 我当前的方法是使用RIGHT JOIN ,但这不会使事件与NULL值组合。

This is what my current statement looks like: 这就是我当前的语句:

SELECT
    a.*,
    b.name

FROM
    a

RIGHT JOIN b
    ON b.id = a.ref_person

ORDER BY 
    a.event,
    b.name

Notice 注意

sqlfiddle seems down, I'll add one as soon as it's up again sqlfiddle似乎下降了,一旦它再次上升,我就添加一个

You want to do a cross join to get all the rows, then case logic to get the task: 您想要进行cross join以获取所有行,然后进行case逻辑以获取任务:

select a.event,
       (case when a.ref_person = b.id then a.task end) as task,
       b.name
from tablea a cross join
     tableb b ;

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

相关问题 左外部联接,带选择,其中右表中的值不返回左中的所有行 - Left outer join with select where value in right table does not return all rows from left 左连接 - Select ALL 来自左表,但 select 仅来自右表的最新 - Left Join - Select ALL from left table but select only the latest from right table mysql 左连接右表最大值 - mysql LEFT join for right table max value 如何通过条件查询(左联接/右联接/内部联接/多选择,…或)从多表中获取数据 - How to fetch data by a conditional query(left join/right join/inner join/ multi select, … or) from multi table 如何选择全左表,条件与右表中的记录匹配? - How to select full left table and where condition match records from right table? LEFT JOIN 右表中的缺失值 - LEFT JOIN missing values from the right table MySQL左连接从一个表中选择最高值 - mysql left join select top value from one table 我如何从选择查询中保留联接值作为表? - how i left join value from select query as table? Laravel 2表联接,左侧表的所有表与具有给定FK值的右侧表的成员合并 - Laravel 2 table join with all from left table merged with members of the right table with a given FK value 内部联接到右表后,SQL查询从左表中选择不同的行 - SQL query to select distinct rows from left table after inner join to the right table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM