简体   繁体   English

查询以获取表中的1行以及该表中引用的另一张表中的许多行

[英]Query to fetch 1 row in table, and many rows from another table, referenced in that row

So I have 2 tables in my database, they are 'workouts' and 'exercises'. 所以我的数据库中有2个表,分别是“锻炼”和“锻炼”。 Workouts contains a row called exercises which is a comma-separated list of exercise IDs - from the 'exercises' table eg '1,2,3'. 锻炼包含一个称为演习的行,它是逗号分隔的演习ID列表-来自“锻炼”表,例如“ 1,2,3”。

My question is, can I write a single query to allow me to select a row from the workouts table, say one with an id of 1, and have MySQL fetch each of the exercises from the list in that row, returning them within the 'workout' row? 我的问题是,我是否可以编写一个查询以允许我从锻炼表中选择一行,例如ID为1的一行,并让MySQL从该行的列表中提取每个练习,然后在“锻炼行?

At the moment I'm using PHP to select the workout row, and then making individual requests for each of the exercises, resulting in serious inefficiency. 此刻,我正在使用PHP选择锻炼行,然后对每个练习进行单独的请求,导致效率低下。

I took a look at Joining rows as array from another table for each row and also did some research into the group_concat() function, but I'm not sure that's what I'm after. 我研究了将行作为另一行的另一个表的数组加入行,并且还对group_concat()函数进行了一些研究,但是我不确定这就是我要的。

Update Here are the 2 tables: 更新这里是2表: 在此处输入图片说明

IMO, the best approach is to redesign your schema to have a cross-reference table called exercises_workouts (or something similar). IMO,最好的方法是重新设计架构,使其具有一个称为exercises_workouts (或类似名称)的交叉引用表。 Remove the CSV field. 删除CSV字段。

Here's page that goes into more detail on implementing a many-to-many relationship: 以下页面将详细介绍如何实现多对多关系:

http://www.tonymarston.net/php-mysql/many-to-many.html http://www.tonymarston.net/php-mysql/many-to-many.html

Note: The linked page uses the mysql_* functions, but the general explanation of the approach stands. 注意:链接的页面使用mysql_ *函数,但是对该方法进行了一般说明。 You'll want to look into PDO for database access. 您将需要研究PDO以进行数据库访问。

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

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