mysql - 不符合条件的sql联合

标签 mysql sql

我有这个查询,它是基于条件的多项选择的联合。 问题是“AND”部分仅应用于最后一个选择,但我想将其应用于整个选择(所有联合)

select * from
(select con.id_contact as  v,substr(concat(ifnull(con.firstname,''),ifnull(con.lastname,'')),1,4) as s0,   null as s1, null as s2 from contact con, fu_rec_group_link g
where con.id_contact = g.id_rec and id_group=125801) as tbl244295 where 1=1   UNION
select * from
(select con.id_contact as v,substr(concat(ifnull(con.firstname,''),ifnull(con.lastname,'')),1,4) as s0, null as s1, null as s2 from contact con, fu_rec_group_link g where
con.id_contact = g.id_rec and id_group=125803) as tbl244296 where 1=1 UNION
select * from
(select con.id_contact as  v,substr(concat(ifnull(con.firstname,''),ifnull(con.lastname,'')),1,4) as s0,  null as s1, null as s2 from contact con, fu_rec_group_link g where
con.id_contact = g.id_rec and id_group=126270) as tbl244297 where 1=1 AND v NOT IN
(select v from (select * from (select con.id_contact as v,substr(concat(ifnull(con.firstname,''),ifnull(con.lastname,'')),1,4) as s0, null as s1, null as s2 from contact con
where id_user=11944 and unregistered is not null) as tbl244299 where 1=1) as tblMinus ) 

最佳答案

正如@jarlh 所指出的那样,您的原始查询的解决方法是将联合包装在另一个选择中,并将最后一个 where 条件应用于该选择。此外,当您使用不带 allunion 时,您可以消除重复项,但这种方式可能代价高昂;最好指定 union all 并使用 distinctgroup by 子句来消除重复行。

但是......看看你的查询,它似乎可以简化很多并减少到下面的查询,它应该呈现相同的结果但性能更好。

select distinct
    con.id_contact as v, 
    substr(concat(ifnull(con.firstname,''),ifnull(con.lastname,'')),1,4) as s0, 
    null as s1, 
    null as s2 
from contact con
join fu_rec_group_link g on con.id_contact = g.id_rec 
where id_group in (125801, 125803, 126270)
and con.id_contact not in (
    select con.id_contact as v
    from contact con
    where id_user=11944 and unregistered is not null
) 

由于既没有任何关于表格设计的信息,也没有任何数据来测试我的假设可能是完全错误的,如果是这样我会立即删除答案。

关于mysql - 不符合条件的sql联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31266343/

相关文章:

php - php 中的多个 MySQL 查询。我试图弄清楚如何使用单选按钮在数据库中搜索多个查询

mysql 详细查询字符串,如通配符

sql - 在sql一对多关系中设置最年轻的时间戳

sql - 设置提交事务失败时的输出参数

mysql - DriverManager.getConnection() 抛出 MySql DB 访问异常

php - 在 Yii 中使用 CD 命令时,如何将两列连接为一列,并且它们之间有一个空格?

java - Java 和 MySQL 中 boolean 变量的位标志

php - Laravel 如何在一个查询中从多个表中删除一行

mysql - 恢复 WordPress 的 SQL 数据库

php - MySQL 连接不工作