0

这个问题是对Is there a standard way to swap a query from an ID to a different column like 'name'?

此查询工作正常:

    SELECT manufacturers.id, manufacturers.name, models.model_manufacturer, models.model_part
    FROM models 
    INNER JOIN manufacturers 
    ON manufacturers.id = models.model_manufacturer
    WHERE model_part = (
        SELECT parts.id 
        FROM parts 
        WHERE parts.name = '{$part_name}')
    GROUP BY manufacturers.id
    ORDER BY name ASC

但是这个,当它遇到一个拥有多个模型的制造商时,失败并显示“子查询返回超过 1 行”:

SELECT parts.id, models.id, models.model_part, models.model_manufacturer, models.name, models.year, models.weight
    FROM parts
    INNER JOIN models
    ON parts.id = models.model_part
    WHERE model_manufacturer = (
        SELECT manufacturers.id 
        FROM manufacturers 
        WHERE manufacturers.name = '{$manufacturer_name}') 
    && model_part = (
        SELECT parts.id 
        FROM parts 
        WHERE parts.name = '{$part_name}')

我不太了解的是,如果我只运行工作示例中的子查询,或者在第二个示例中单独运行子查询,它们都返回一个值。如果我运行任一整个查询,它们都会返回多个值。那么为什么一个错误而另一个没有呢?在 myPHPAdmin 中运行查询可以正常工作,但是当我尝试在我的 PHP 文件中执行此操作时失败。

4

2 回答 2

4

但是这个,当它遇到一个拥有多个模型的制造商时,失败并显示“子查询返回超过 1 行”

MySQL=运算符可以将 1 个值与另一个值进行比较。当子查询返回更多,然后是 1 个值时,它会感到困惑,因为它不知道与哪个进行比较。

使用IN运算符而不是=

SELECT parts.id, models.id, 
    models.model_part, models.model_manufacturer, 
    models.name, models.year, models.weight
FROM parts
INNER JOIN models
ON parts.id = models.model_part
WHERE model_manufacturer = (
        SELECT manufacturers.id 
        FROM manufacturers 
        WHERE manufacturers.name = '{$manufacturer_name}') 
    && model_part IN (
        SELECT parts.id 
        FROM parts 
        WHERE parts.name = '{$part_name}')

抱歉,如果我将 IN 运算符放在不正确的位置。但我认为,model_part 的第二个子查询是正确的地方。

于 2013-07-12T22:46:49.423 回答
1

IN 的上述建议可能是最简单的想法。

不过,我很想将其重新编码为 JOIN,使用 DISTINCT 删除重复项:-

SELECT DISTINCT parts.id, models.id, models.model_part, models.model_manufacturer, models.name, models.year, models.weight
    FROM parts
    INNER JOIN models
    ON parts.id = models.model_part
    INNER JOIN manufacturers
    ON models.model_manufacturer = manufacturers.id AND manufacturers.name = '{$manufacturer_name}'
    INNER JOIN parts parts2 ON models.model_part = parts2.id AND parts.name = '{$part_name}'
于 2013-07-12T22:50:20.680 回答