简体   繁体   English

MySql 加入一对多

[英]MySql join for one to many

I want to join a couple of tables that have a one to many relationship, but I'm having trouble working out how to do it.我想加入几个具有一对多关系的表,但我不知道如何去做。

I have one table with a list of items, and a second table which has a list of their ids against user id and an action.我有一个包含项目列表的表,以及第二个表,其中包含针对用户 ID 和操作的 ID 列表。 Each user can only have one action against each item, and I want to join these in such a way that I get an output with the item along with the action performed by each user.每个用户只能对每个项目有一个操作,我想以这样一种方式加入这些操作,以便我获得项目的输出以及每个用户执行的操作。

items table项目表

item_id name
1       Desk
2       Phone
3       Fax

actions table动作表

item_id user_id action
1       1       sell
1       2       buy
1       3       sell
2       1       sell
2       2       buy
2       3       sell
3       1       sell
3       3       sell

desired output期望的输出

item_id name  user_id1 user_id2 user_id3
1       Desk  sell     buy      sell
2       Phone sell     buy      sell
3       Fax   sell     NULL     sell

Many thanks非常感谢

If you know the users in advance, you can use conditional aggregation:如果您事先了解用户,则可以使用条件聚合:

select i.item_id, i.name,
  max(case when a.user_id = 1 then a.action end) as user_1,
  max(case when a.user_id = 2 then a.action end) as user_2,
  max(case when a.user_id = 3 then a.action end) as user_3
from items i left join 
  actions_table a 
  on a.item_id = i.item_id
group by i.item_id, i.name;

If you want to handle a variable number of users, then you cannot use a simple select because the columns in a select have to be explicitly defined.如果你想处理可变数量的用户,那么你不能用一个简单的select ,因为在列select必须被明确定义。 One method is dynamic SQL, where you construct the SQL with all the users (using logic similar to the above).一种方法是动态 SQL,您可以在其中使用所有用户构建 SQL(使用类似于上述的逻辑)。 Another method would store the results using JSON.另一种方法是使用 JSON 存储结果。

It will be better if we are using modern sql wrap functin for this problem, but unfortunatelly there is still no factory function available until now.如果我们使用现代 sql wrap functin 来解决这个问题会更好,但不幸的是,直到现在仍然没有可用的工厂函数。 So it seems we should create any user defined extension to be embedded into the system (engine) or manipulate the resultset (query result) from application layer as an alternative.因此,似乎我们应该创建任何用户定义的扩展以嵌入系统(引擎)或从应用程序层操作结果集(查询结果)作为替代方案。

Otherwise we can also use ANSI/ISO Join to solve this problem easily.否则我们也可以使用ANSI/ISO Join来轻松解决这个问题。

Select items.*, a1.action user_id1, a2.action user_id2, a3.action user_id3
From items
Left Join actions a1
 On items.id = a1.item_id and a1.user_id = 1
Left Join actions a2
 On items.id = a2.item_id and a2.user_id = 2
Left Join actions a3
 On items.id = a3.item_id and a3.user_id = 3

Hope my answer could help.希望我的回答能有所帮助。

Cheers.干杯。

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

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