Mysql查询,选择2个数据库,4个表+嵌套SELECT?

时间:2009-11-24 10:28:52

标签: mysql database nested

这是我目前的查询:

$sel = "SELECT 
        db1t1.userid, db1t1.customer_id, db2t1.customers_id, db2t1.orders_id, db2t2.products_price
    FROM 
        database1.table1 db1t1
        LEFT JOIN database2.table1 db2t1 ON
            db1t1.customer_id = db2t1.customers_id
        LEFT JOIN database2.table2 db2t2 ON
            db2t1.orders_id = db2t2.orders_id   
    WHERE db1t1.userid IN(
        SELECT 
            l.userid, l.username, r.username, r.cus_id 
        FROM 
            database1.table3 l
            LEFT JOIN database2.table4 r ON
                l.username = r.username
        WHERE r.cus_id = '1234'
        )";

错误讯息:

  

操作数应包含1列

1 个答案:

答案 0 :(得分:0)

发生错误是因为您将具有多个列的结果返回到IN子句。

试试这个:

SELECT 
    `db1t1`.`userid`, `db1t1`.`customer_id`, `db2t1`.`customers_id`,
    `db2t1`.`orders_id`, `db2t2`.`products_price`
FROM `database1`.`table1` AS `db1t1`
    LEFT JOIN `database2`.`table1` AS `db2t1` 
        USING (`customers_id`)
    LEFT JOIN `database2`.`table2` AS `db2t2`
        USING (`orders_id`)  
WHERE `db1t1`.`userid` IN (
    SELECT `l`.`userid`
    FROM `database1`.`table3` AS `l`
        LEFT JOIN `database2`.`table4` AS `r`
            USING (`username`)
    WHERE `r`.`cus_id` = 1234
)

你想要达到什么目的?也许我们可以找到更好的解决方案。

另外,我认为你应该在子查询中进行INNER JOIN而不是LEFT JOIN。