Mysql查询连接表,如果值相同则填充空

时间:2017-11-15 10:24:38

标签: mysql

我加入2桌有问题 这是mysql查询

  

选择*   来自tbl_perspective a   内部联接tbl_objective b on b.idperspective = a.idperspective

结果是: Query Result

我想显示第一行的perspectivename和空白或null

最终结果: enter image description here

4 个答案:

答案 0 :(得分:0)

加入一个子查询,该子查询标识每个idperspective组的第一行:

SELECT t1.*
FROM tbl_perspective t1
INNER JOIN
(
    SELECT idperspective, MIN(idobjective) AS min_idobjective
    FROM tbl_perspective
    GROUP BY idperspective
) t2
    ON t1.idperspective = t2.idperspective AND
       t1.idobjective   = t2.min_idobjective;

答案 1 :(得分:0)

您需要使用LEFT JOIN来包含所有结果,例如:https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

答案 2 :(得分:0)

嗨Anwr Rawk只需你可以使用LEFT JOIN

 select * from tbl_perspective as a 
     left join 
 tbl_objective as b 
 on b.idperspective=a.idperspective

答案 3 :(得分:0)

感谢您的回答,2表加入时确定没关系,但加入3表时我有问题。这是我的查询

    select 
case when b.idobjective=(select min(idobjective) from tbl_objective where idperspective=c.idperspective) then c.perspectivename end as perspectivename,
case when a.idindicator=(select min(idindicator) from tbl_indicator where idobjective=a.idobjective) then b.objectivename end as objectivename,
a.indicatorname
from tbl_indicator a
inner join tbl_objective b on b.idobjective=a.idobjective
inner join tbl_perspective c on c.idperspective=b.idperspective

此图片是结果查询,但我希望仅在财务时显示财务,并且所有行都显示为null this result