使查询内部查询结果可选

时间:2013-12-10 09:29:37

标签: mysql sql function select nested

我想知道是否有可能以某种方式使用MySQL,包装内部查询的选择,以便外部查询可以在其where子句中使用它。

SELECT  
`FirstName`,
`Surname`,
`AddressLine1`,
`AddressLine2`,  
`AddressLine3`,  
`AddressLocale`,
`AddressRegion`, 
`AddressZip`,
`AddressCountry`,
`CopyShipAddress`
FROM  `Contacts` 
WHERE `EEID` 
IN 
(SELECT CONCAT_WS(',', `Sender`,  `Receiver`,  `Buyer` ) AS EEID_list
FROM  `Transactions` 
WHERE  `TransactionID` = 3)

SenderReceiverBuyer是EEID。也许我可以使用除CONCAT_WS以外的功能,它将为我提供此功能。

1 个答案:

答案 0 :(得分:1)

不要在IN查询中使用concat_ws记录,它可能无法提供正确的数据

concat_ws可以完美地用于整数的IN查询,但可能不适用于字符串,因为它们需要用引号括起来

尝试以下

SELECT  
`FirstName`,
`Surname`,
`AddressLine1`,
`AddressLine2`,  
`AddressLine3`,  
`AddressLocale`,
`AddressRegion`, 
`AddressZip`,
`AddressCountry`,
`CopyShipAddress`
FROM  `Contacts` 
WHERE `EEID` 
IN 
(
select Sender as eeid FROM Transactions WHERE TransactionId=3
UNION ALL
select Receiver as eeid FROM Transactions WHERE TransactionId=3
UNION ALL
select Buyer as eeid FROM Transactions WHERE TransactionId=3
 )