1

I am having a pretty complicated query. What I have is a table with car parts (parts_list, about 600 rows) which contains some information about the part like it's name and if it's motor dependent or not. For motor dependency I am having two different queries, so this is the one with no motor dependency (0, I save it as a boolean). Most of the parts can be disassembled and broken into more parts, that's why I am saving the parts as a tree and in that query I take only the parts that can't be disassembled (tree leaves). This table represents only the list of possible parts. Now for each car model I save a row in another table (parts) and I stick the parts_list_id and model_id together and then the price and quantity. Now if I run the query it will successfully generate about 500 rows(taking only the leaf parts) in the table "parts" and it will do what I need. About 500 (leaf) parts for the model id. But sometimes I generate a row for another model for a specific part. And then the query doesn't make the rest 499 rows. It only works if WHERE NOT EXISTS select query gives back 0. If even one row exists it doesn't insert the rest. But it doesn't make sense to me, because shouldn't it check with different values like a loop?

INSERT INTO parts  (parts_list_id, model_id, motor_id)
SELECT      orig1.id, '" . $this->model_id . "', '0'
FROM        parts_list AS orig1
LEFT JOIN   parts_list AS orig2 ON ( orig1.id = orig2.parent_id )
WHERE       orig2.id IS NULL
AND         orig1.motor_dependent = '0'
AND NOT EXISTS (
  SELECT      t1.id
  FROM        parts_list AS t1
  LEFT JOIN   parts_list AS t2 ON ( t1.id = t2.parent_id )
  LEFT JOIN   parts ON ( parts.parts_list_id = t1.id )
  WHERE       t2.id IS NULL
  AND         t1.motor_dependent = '0'
  AND         parts.parts_list_id = t1.id
  AND         parts.model_id = :model_id
)
4

1 回答 1

0

好吧,sql语句似乎很好。如果只有一行,NOT EXISTS 返回 false。这是正确的。没有插入任何行。也许您想使用parts_list_id NOT IN(您的子查询)而不是NOT EXISTS 进行一些不同的检查。

NOT EXISTS 表示集合作为一个整体的条件,NOT IN 用于确定集合是否具有正确的项。

我希望能做对。仅从单个语句中理解您的域有点困难。

于 2013-05-10T11:13:09.857 回答