使用连接表中的值连接多个表

时间:2012-11-01 16:03:46

标签: php mysql codeigniter join where-clause

我有以下表格:

systems
-----------
id
name
price
online
productid


specifications
-------------
id
systemid
type
componentid
quantity


components
-------------
id
name
brand
type
description

我需要使用多个选项过滤这些表。每个系统都有多个规范行,每个“规范”行链接到它对应的“组件”行。

我的问题是:

我需要能够根据表连接按多个属性过滤系统。我一直在使用代码,它将允许我1个搜索选项,但没有更进一步:

select
    `systems`.`id`,
    `systems`.`name`, 
    `specifications`.`type` 
from `systems` 
    join specifications 
        on `systems`.`id` = `specifications`.`systemid` 
    join components 
        on `specifications`.`componentid` = `components`.`id`
where 
    `specifications`.`type` = 'cpu' 
    and `components`.`brand` = 'amd'

所以,这将让我做一个规格类型为CPU且品牌为AMD的联接,但是如果我添加其他东西来查找,例如specifications.type ='graphics' AND components.brand = 'nvidia'它就不起作用。我认为这是加入工作方式所固有的,正如我所说,我在这里解决问题很困难,因为我对这些更复杂的数据库事务都很陌生,并且非常希望能指出正确的方向! / p>

我正在使用CodeIgniter作为我的框架,我想尝试通过MySQL获取底层,而不是在PHP中使用它 - 如果有可能的话 - 因为我想更好地了解正在发生的事情这里。

2 个答案:

答案 0 :(得分:1)

你的意思是说

select `systems`.`id`,`systems`.`name`, `specifications`.`type` from `systems`
join specifications on `systems`.`id` = `specifications`.`systemid` 
join components on `specifications`.`componentid` = `components`.`id`
where 
     (`specifications`.`type` = 'cpu' AND `components`.`brand` = 'amd') OR
     (`specifications`.`type` = `graphics` AND `components`.`brand` = `nvidia`)

不起作用?

这样的事情

SELECT S.`id`, S.`name`, P.`type` FROM `systems` S 
JOIN `specifications` P ON S.`id` = P.`systemid`
WHERE S.`id` IN (

    SELECT S2.`systemid` AS id FROM `specifications` S2
    JOIN `components` C2 ON S2.`componentid` = C2.`id`
    WHERE S2.`type` = 'cpu' AND c2.`brand` = 'amd'
) AND S.`id` IN (

    SELECT S3.`systemid` AS id FROM `specifications` S3
    JOIN `components` C3 ON S3.`componentid` = C3.`id`
    WHERE S3.`type` = 'graphics' AND c3.`brand` = 'nvidia'
)

答案 1 :(得分:0)

好的,通过让每个查询作为子查询运行,我已经完成了它。

因此,它将具有AMD处理器的系统的所有ID返回到查找具有NVIDIA图形卡的所有系统的条件IN子句。

SELECT  `systems`.`id` ,  `systems`.`name` ,  `specifications`.`type` 
FROM  `systems` 
JOIN specifications ON  `systems`.`id` =  `specifications`.`systemid` 
JOIN components ON  `specifications`.`componentid` =  `components`.`id` 
WHERE (
    `specifications`.`type` =  'graphics'
    AND  `components`.`brand` =  'nvidia'
    )
AND (
    `systems`.`id` IN (
          SELECT  `systems`.`id` 
          FROM  `systems` 
          JOIN specifications ON  `systems`.`id` =  `specifications`.`systemid` 
          JOIN components ON  `specifications`.`componentid` =  `components`.`id` 
     WHERE (
          `specifications`.`type` =  'cpu'
          AND  `components`.`brand` =  'amd'
          )
     )
 )

以编程方式,我发现它非常繁琐,而且我不确定它是如何叠加效率的 - 作为一个很大程度上自学成才的程序员,我总是试图确保我以“正确”的方式做事。任何人都可以通过这种方式看到任何问题吗?让CodeIgniter返回那组ID更好吗?

请记住,这个问题有所简化,最终会包含几个子查询 - 尽管网站本身永远不会受到大量负担。

相关问题