简体   繁体   English

MySQL查询从数组值查询另一个表

[英]MySQL Query to query another table from array value

I have a table which one column contains a comma seperated value. 我有一张表,其中一列包含一个逗号分隔的值。 I need to, within the query, get those values, explode them, and do a query to another table. 我需要在查询中获取这些值,将它们分解,然后对另一个表进行查询。

Let me explain the structure. 让我解释一下结构。

Table 1: courses. 表1:课程。 Columns we are worried about for this example: 对于此示例,我们担心的列:

courses.id, courses.products

This will return a value 这将返回一个值

$query['id']-> 1000
$query['products']-> 1,5

Within the query I need to pull the product name for each product from the products table 在查询中,我需要从产品表中提取每个产品的产品名称

so 所以

products.productname

even if i have to create 5 productname columns in the query because no one should have more than 5 products. 即使我必须在查询中创建5个productname列,因为没有人可以拥有5个以上的产品。

The point of all of this is I have to dump this to a spreadsheet and i need to have the product names in there. 所有这些的重点是我必须将其转储到电子表格中,并且我需要在其中具有产品名称。

To accomplish the CSV dump I have this code. 要完成CSV转储,我需要以下代码。 ( I already have the query written however right now just returning "1,5" instead of product names (我已经写了查询,但是现在只返回“ 1,5”而不是产品名称

 $query = " QUERY GOES HERE ";
 $result = mysql_query($query, $db) or die(mysql_error());
 if (!$result) die('Couldn\'t fetch records'); 
 $num_fields = mysql_num_fields($result); 
 $headers = array(); 
 for ($i = 0; $i < $num_fields; $i++) 
 {     
        $headers[] = mysql_field_name($result , $i); 
 } 
 $fp = fopen('php://output', 'w'); 
 if ($fp && $result) 
 {     
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="export.csv"');
        header('Pragma: no-cache');    
        header('Expires: 0');
        fputcsv($fp, $headers); 
        while ($row = mysql_fetch_row($result)) 
        {
         fputcsv($fp, array_values($row)); 
      }
 die; 
 } 

A quick solution for your case: 针对您的情况的快速解决方案:

$course_id = intval( $_GET['id'] );
// get the id 1000
$result = mysql_query( "SELECT `products` FROM `courses` WHERE `id`=" . $course_id );
$course = mysql_fetch_assoc( $result ) or exit( "Invalid ID" );
$result = mysql_query( "SELECT `id`,`productname` FROM `products` WHERE `id` IN (".$course['products'].")" );
// this will result in "SELECT id,productname FROM products WHERE id IN (1,5)"
//
// rest of your code

If you don't export your data every second or so you should be fine with these two queries. 如果您不每秒导出一次数据,那么对这两个查询应该没问题。

You now experience why it is bad database design to store multiple values comma separated in a single database field. 您现在将了解为什么在单个数据库字段中存储多个以逗号分隔的值是不好的数据库设计。 If you are restructuring the application this would be a good time to refactor your database and store every product <-> course affiliation in a single row. 如果要重组应用程序,那么这将是重构数据库并将每个产品<->课程从属关系存储在一行中的好时机。 If your courses table only has these two columns, you can do it like this: 如果您的courses表仅包含这两列,则可以这样操作:

id   | product
--------------
1000 | 1
1000 | 5

If your table has more fields related to the course, you should move the column products into its own table as pictured above. 如果您的表中有更多与课程相关的字段,则应将列products移动到其自己的表中,如上图所示。 That's the usual database structure for a many to many relationship. 这是多对多关系的常用数据库结构。

Initially I expected to get your results in a single query with one of these queries, but for some reason I always end up with only one record, and I currently don't have the time to drill deeper into it. 最初,我希望使用其中一个查询在单个查询中获得结果,但是由于某种原因,我总是只获得一条记录,而我目前没有时间进行更深入的研究。

-- try #1
SELECT products.id,products.productname 
FROM products JOIN courses ON products.id IN (courses.products)
WHERE courses.id=1000

-- try #2
SELECT products.id,products.productname 
FROM products 
WHERE products.id IN (
    SELECT courses.products 
    FROM courses 
    WHERE courses.id=1000
)

Last, but not least, you've already been given the advice to stop using the deprecated mysql_* functions. 最后但并非最不重要的一点是,已经为您提供了停止使用不推荐使用的mysql_*函数的建议。 I know it's difficult to rewrite an existing application, I've been down that road myself. 我知道重写现有的应用程序很困难,我自己一直走那条路。 My experience is that it is best to do this along the way, just define a second database connection using mysqli or PDO, whatever you are more comfortable with. 我的经验是,最好在此过程中执行此操作,只需使用mysqli或PDO定义第二个数据库连接即可,无论您喜欢什么。 Every time you change something database related in a script rewrite it with the newer API. 每次更改脚本中与数据库相关的内容时,都会使用较新的API对其进行重写。 You will have a little more overhead while you do this, but not noticeably and it is way easier than rewriting everything at once. 执行此操作时,您会有更多的开销,但并不明显,这比一次重写所有内容容易得多。

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

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