繁体   English   中英

Mysql 在多个条件下右连接不起作用

[英]Mysql Right join with mutiple condtion not working

我有两个表 table1 和 table2 并且当将 table2 与 table1 正确连接时,我没有得到该行。 在这里,我还附上了小提琴链接

小提琴墨水

CREATE TABLE `table1` (
 `orderid` int(11) NOT NULL AUTO_INCREMENT,
 PRIMARY KEY (`orderid`)
);
CREATE TABLE `table2` ( `fields_id` INT NOT NULL AUTO_INCREMENT , `table1_order_id` INT(11) NOT NULL , `field_value` VARCHAR(100) NOT NULL , `fname` VARCHAR(100) NOT NULL , PRIMARY KEY (`fields_id`)) ENGINE = InnoDB;

INSERT INTO `table1` (`orderid`) VALUES (1), (2), (3), (4), (5), (6);
INSERT INTO `table2` (`fields_id`, `table1_order_id`, `field_value`, `fname`) VALUES (NULL, '1', 'karthi', 'name');
INSERT INTO `table2` (`fields_id`, `table1_order_id`, `field_value`, `fname`) VALUES (NULL, '2', 'karthi', 'name');
INSERT INTO `table2` (`fields_id`, `table1_order_id`, `field_value`, `fname`) VALUES (NULL, '3', 'selva', 'name');
INSERT INTO `table2` (`fields_id`, `table1_order_id`, `field_value`, `fname`) VALUES (NULL, '1', 'salem', 'city');
INSERT INTO `table2` (`fields_id`, `table1_order_id`, `field_value`, `fname`) VALUES (NULL, '2', 'chennai', 'city');
INSERT INTO `table2` (`fields_id`, `table1_order_id`, `field_value`, `fname`) VALUES (NULL, '3', 'mumbai', 'city');

select table1.*
from table1 
right JOIN table2 ON (
        table2.table1_order_id = table1.orderid 
        AND 
            ( table2.field_value LIKE '%karthi%' 
            AND table2.fname = 'name' ) 
        AND ( 
            table2.field_value LIKE '%salem%' 
            AND table2.fname = 'city' 
        ) 

    ) 

    where 1 group by table1.orderid

上面我写了 select 查询,但它返回 null 结果,但我期待 output 如下所示,

订单号 1

您必须将AND子句更改为OR子句,您将获得如下两条记录:

select table1.*
from table1 
right JOIN table2 ON
        table2.table1_order_id = table1.orderid 
    where 
            ( table2.field_value LIKE '%karthi%' 
            AND table2.fname = 'name' ) 
        OR ( 
            table2.field_value LIKE '%salem%' 
            AND table2.fname = 'city' 
        ) 

    group by table1.orderid

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM