mysql - 从2个sql查询的Union中获取不同的值

时间:2016-05-18 02:35:18

标签: mysql

早上好,

我试图从两个sql查询的联合中获取所有不同的值,并根据它们的标记进行查询。

SELECT t.id, t.tag, bd.owner, bp.param_value as role
FROM baseData db
LEFT JOIN baseParam bp ON bp.`status` = "active" AND bp.param_name = "role" AND bp.base_data_id = bd.id
RIGHT JOIN tag t ON t.base_data_id = bp.base_data_id AND t.`status` = "active"
WHERE bd.`status` = "active" AND bd.application = "template" 
AND (((bp.param_value = "public" OR bp.param_value IS NULL)))
GROUP BY t.tag

UNION

SELECT t.id, t.tag, bd.owner, bp.param_value as role
FROM baseData bd
LEFT JOIN baseParam bp ON bp.`status` = "active" AND bp.param_name = "role" AND bp.base_data_id = bd.id
RIGHT JOIN tag t ON t.base_data_id = bp.base_data_id AND t.`status` = "active"
INNER JOIN resTemplate cr ON cr.base_data_id = bd.id
WHERE bd.`status` = "active" AND bd.application = "template" AND cr.`status` = "active"
AND (((bp.param_value = "private" OR bp.param_value IS NULL))) 
GROUP BY t.tag;

两个查询都来自同一个表,唯一的区别是他们的角色是“公共”和“私人”。私人也有另一张桌子的考虑因素。此查询返回此表

enter image description here

在此表中的

,如红色框中所示,在Tag列中,重复了Group。以及其他一些标签名称。 如何更改我的SQL查询以过滤它以使Tag列不同?

1 个答案:

答案 0 :(得分:0)

请试试这个;)

SELECT * FROM
    (SELECT t.id, t.tag, bd.owner, bp.param_value as role
    FROM baseData db
    LEFT JOIN baseParam bp ON bp.`status` = "active" AND bp.param_name = "role" AND bp.base_data_id = bd.id
    RIGHT JOIN tag t ON t.base_data_id = bp.base_data_id AND t.`status` = "active"
    WHERE bd.`status` = "active" AND bd.application = "template" 
    AND (((bp.param_value = "public" OR bp.param_value IS NULL)))

    UNION

    SELECT t.id, t.tag, bd.owner, bp.param_value as role
    FROM baseData bd
    LEFT JOIN baseParam bp ON bp.`status` = "active" AND bp.param_name = "role" AND bp.base_data_id = bd.id
    RIGHT JOIN tag t ON t.base_data_id = bp.base_data_id AND t.`status` = "active"
    INNER JOIN resTemplate cr ON cr.base_data_id = bd.id
    WHERE bd.`status` = "active" AND bd.application = "template" AND cr.`status` = "active"
    AND (((bp.param_value = "private" OR bp.param_value IS NULL)))) TMP
GROUP BY tag;