简体   繁体   English

MySQL找到名称为“ x”的result_id,然后删除共享该结果ID和名称为“ y”的其他条目

[英]Mysql find result_id where name = “x” then delete other entries that share that result_id and name=“y”

I'm using a mixture of php and mysql to do the following query and I'm sure there must be a way to do it in just SQL. 我正在使用php和mysql的混合物来执行以下查询,并且我确定必须有一种方法可以在SQL中完成。 I've stripped out some of the code and left enough that you should be able to see what I'm trying to accomplish. 我已经删除了一些代码,并留下了足够的内容,您应该能够看到我要完成的工作。

Any help would be much appreciated! 任何帮助将非常感激!

SELECT result_id FROM categories
WHERE name = "conventional"


foreach ( $results as $row ){
    $query = "
    DELETE FROM categories
    WHERE result_id = $row->result_id && (name = 'va' OR name = 'fha' OR name = 'usda' OR name = 'other')
    ";
    $this->db($query);
} 

EDIT: From the answers I've received so far, I don't think I've explained this well enough. 编辑:从到目前为止我收到的答案中,我认为我对此解释不够充分。 the columns in this table are id, result_id, name 该表中的列是id,result_id,name

There are multiple entries that share the same result_id as they relate to entries in the "results" table. 有多个条目共享相同的result_id,因为它们与“结果”表中的条目相关。 So I'm trying to find the result_id's of entries with the name "conventional" so I can find all the entries with the same result_id and delete them if their names are "va", "fha", "usda" or "other" 因此,我正在尝试查找名称为“常规”的条目的result_id,以便我可以找到具有相同result_id的所有条目,并在名称为“ va”,“ fha”,“ usda”或“ other”的情况下将其删除

DELETE FROM categories 
WHERE name IN ("va", "fha", "usda", "other")
AND result_id IN (
  SELECT result_id FROM categories
  WHERE name = 'conventional'
)

You want to avoid delete query in loop and here is how to do it: 您想要避免循环中的删除查询,这是如何做到的:

SELECT result_id FROM categories
WHERE name = "conventional"

// Now build csv of ids    
$arx = array();
foreach ( $results as $row ) {
    $arx[] = $row->result_id;
} 

if(!empty($arx)) {
    $arx_1 = implode(',', $arx);
    $query = "DELETE FROM categories
    WHERE result_id in ({$arx_1}) AND (name = 'va' OR name = 'fha' OR name = 'usda' OR name = 'other')";

    $this->db($query);
}

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

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