鉴于这两个表idcontype
中的idinfcontype
和containers
与id
中的contypes
相关。
我需要一个查询,为containers
和descrip
返回idcontype
行idinfcontype
列。
--
-- Table structure for table `containers`
--
`id` int(11) NOT NULL AUTO_INCREMENT,
`idarticle` int(11) NOT NULL,
`idzone` int(3) NOT NULL DEFAULT '1',
`idcontype` int(11) NOT NULL DEFAULT '1',
`idinfcontype` int(11) NOT NULL DEFAULT '0',
--
-- Table structure for table `contypes`
--
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` char(1) COLLATE utf8_spanish_ci NOT NULL,
`code` varchar(2) COLLATE utf8_spanish_ci NOT NULL,
`level` tinyint(1) NOT NULL,
`descrip` varchar(16) COLLATE utf8_spanish_ci NOT NULL,
idcontype
中的{p> idinfcontype
和containers
与id
中的contypes
相关
idcontype
始终与id
中的contypes
相关,但idinfcontype
可能为0
此查询生成三行,其中包含重复的行
SELECT DISTINCT * FROM
(SELECT `containers`.`id`,`idarticle`,`idcontype`,`descrip` FROM `containers` JOIN `contypes` ON containers.idcontype=contypes.id
UNION
SELECT `containers`.`id`,`idarticle`,`idinfcontype`,`descrip` FROM `containers` JOIN `contypes` ON containers.idinfcontype=contypes.id
) CT
Rows: 3
id idarticle idcontype descrip
1 2 1 PACKAGE
2 2 2 BOX
2 2 1 PACKAGE
经过一番努力,这个查询会产生所需的结果:
SELECT * FROM `containers`
JOIN
(SELECT DISTINCT id AS idc FROM
(SELECT `containers`.`id`,`idarticle`,`idcontype`,`descrip` FROM `containers` JOIN `contypes` ON containers.idcontype=contypes.id
UNION
SELECT `containers`.`id`,`idarticle`,`idinfcontype`,`descrip` FROM `containers` JOIN `contypes` ON containers.idinfcontype=contypes.id
) CT ) CTD
ON containers.id=idc
id idarticle idcontype descrip
1 2 1 PACKAGE
2 2 2 BOX
有更简单的方法吗?
答案 0 :(得分:0)
您可以使用相关名称多次加入同一个表:
SELECT `containers`.`id`,`idarticle`,`idcontype`,`contypes`.`descrip`, 'idinfcontype', c2.'descrip'
FROM `containers`
JOIN `contypes` ON containers.idcontype='contypes'.contypes.id
JOIN `contypes` c2 ON containers.idinfcontype=c2.id
第二个contypes表的相关名称为c2。第一个contypes表没有提供相关名,因此使用表名本身作为相关名。后者也适用于容器表。
答案 1 :(得分:0)
通常,您可以使用left join
s:
SELECT c.*, ct.descrip, ctinf.descrip as infdescrip
FROM containers c LEFT JOIN
contypes ct
on c.idcontype = ct.id LEFT JOIN
contypes ctinf
on c.idinfcontype = ctinf.id;
除left join
之外,此查询:
from
子句中具有相同的表两次。