在mysql select语句中重用内部查询

时间:2014-06-13 06:53:08

标签: mysql sql

mysql> select a.catname as parent , b.catname as child from cmscat a , cmscat b where  
a.catrefid = (select ccmcatrefid1 as parentId from cmsccm where ccmrefid = 141) and 
b.catrefid= (select ccmcatrefid2 as childId from cmsccm where ccmrefid = 141);

+--------------+-----------------+
| parent       | child           |
+--------------+-----------------+
| Ceiling Fans | Decorative fans |
+--------------+-----------------+

这可能是一个非常基本的问题,我从查询中得到了我想要的东西, 我只是想知道有没有办法缩短这个查询

我正在寻找一种可以使用以下查询的方式

select ccmcatrefid1 as parentId ,ccmcatrefid2 as childId from cmsccm 
where ccmrefid = 141;

而不是分别查询childId和parentId。

-------------------------------------------- ------ 表结构

1 cmscat (category table)
it have (catrefid , catname)

2 cmsccm (category mapping table, it maps category as parent and child)
if have (ccmrefid ,ccmcatrefid1, ccmcatrefid2)
where ccmcatrefid1 and ccmcatrefid2 are id of cmscat table(catrefid)

2 个答案:

答案 0 :(得分:2)

使用3向JOIN:

SELECT a.catname AS parent, b.catname AS child
FROM cmsccm AS c
JOIN cmscat AS a ON a.catrefid = c.ccmcatrefid1
JOIN cmscat AS b ON b.catrefid = c.ccmcatrefid2
WHERE c.ccmrefid = 141

答案 1 :(得分:0)

所以你想只访问一次表?然后加入两个,以便得到两个有问题的记录。然后使用case构造来获取一个或另一个名称,然后聚合以获得一行显示两个名称。

select 
  max(case when cmscat.catrefid = cmsccm.ccmcatrefid1 then cmscat.catname end) as parentname,
  max(case when cmscat.catrefid = cmsccm.ccmcatrefid2 then cmscat.catname end) as childname
from cmscat
join cmsccm on cmscat.catrefid in (cmsccm.ccmcatrefid1, cmsccm.ccmcatrefid2)
where cmsccm.ccmrefid = 141;