简体   繁体   English

如何在一个 mysql 查询中从一个表中获取值以及从另一个连接表中获取值数组?

[英]How can I get value from one table and array of values from another join table in one mysql query?

I have a table called lists and a join table called items_to_lists .我有一个名为列表的表和一个名为items_to_lists的连接表。

I want to query and return all lists for a particular user:我想查询并返回特定用户的所有列表:

SELECT lists.* FROM lists WHERE lists.user_id = 'someUserID'

But I also want to include in this query all of the item_id values in the join table as an array for each list.但我也想在这个查询中包含连接表中的所有 item_id 值作为每个列表的数组。 Is this possible?这可能吗? What I want to be returned is:我想被退回的是:

list_id = ... , user_id = ... [deck_id1, deck_id2, etc] for each list.

What I have tried is:我尝试过的是:

SELECT lists.*, items_to_lists.item_id FROM lists INNER JOIN items_to_lists ON items_to_lists.list_id = lists.list_id WHERE lists.user_id = 'someUserID'

This returns each relation as a separate row rather than an array associated with each list.这将每个关系作为单独的行返回,而不是与每个列表关联的数组。 Is there anyway to return the list row with an array of the join table item_id's?无论如何要返回带有连接表 item_id 数组的列表行吗?

GROUP_CONCAT has some more Options like choosing the SEPERAOTR or Ordering the ids GROUP_CONCAT有更多选项,例如选择 SEPERAOTR 或订购 ID

SELECT l.*, CONCAT('[',GROUP_CONCAT(DISTINCT il.item_id) ,']')
FROM lists l INNER JOIN items_to_lists il ON il.list_id = l.list_id 
WHERE l.user_id = 'someUserID'

You could use GROUP_CONCAT with GROUP BY , something like this:您可以将GROUP_CONCATGROUP BY一起使用,如下所示:

SELECT
  lists.list_id, GROUP_CONCAT(items_to_lists.item_id)
FROM lists INNER JOIN items_to_lists ON items_to_lists.list_id = lists.list_id
WHERE
  lists.user_id = 'someUserID'
GROUP BY
  lists.list_id

暂无
暂无

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

相关问题 MYSQL - 如果值不存在于另一表中,则查询从一个表中获取值 - MYSQL - Query to get values from one table if the value doesn't exist in another table 如何从表中的两个查询中获取常用值并将其与MySql中的另一个表连接? - How I get common values from two query in a table and join it with another table in MySql? 如何标记一个表中的值,而不是另一表(mySQL)中的值? - How can I mark the values from one table, that are not in another table (mySQL)? MySQL联接/求和来自一个表列的值与来自另一个表的计数值 - MySQL join / sum value from one table colum with a count values from another 如何在同一选择查询中将一个表中的值交换到另一表中的值? - How can I swap a value from one table to that of another table in the same select query? 如何从同一mysql表的另一行中的值中减去一行中的值 - How can I subtract the values in one row from the values in another row in the same mysql table MYSQL-如何从第一个表返回数组,并在一个查询中使用该数组从另一个表中选择? - MYSQL - How to return array from first table and select from another table using that array in one query? 我应该如何在MySQL中编写查询以从一个表获取值到另一个表 - How should i write query in MySQL for getting values from one table to another MySQL从具有联接的另一个表中获取结果 - Mysql get results from one table based on another with join 从mysql中的另一个表加入一行 - join one row from another table in mysql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM