0

I have a coin table which provides all the information about uploaded coins, and there is an owner table which gives information about the owner of a particular coin. In the coin_owners table, there is field 'ownership_mode' which will be either 'transfer' or 'Reward'. If the mode is 'transfer', I want to left join the transfer table, and if the mode is 'Reward', I want to join the rewards table.

I have tried this using the CASE clause, but it's not working.

The query I tried is:

SELECT * , coins.id AS CoinId FROM coins
LEFT JOIN coin_owners ON coin_owners.coin_id = coins.id
LEFT JOIN (CASE WHEN coin_owners.`ownership_mode` = 'transfer' THEN transfer_detail ON   transfer_detail.transfer_to = coin_owners.current_owner
AND transfer_detail.transfer_from = SUBSTRING_INDEX( coin_owners.previous_owner,  ',',  '-1' )  
WHEN coin_owners.`ownership_mode` = 'Reward' THEN rewards ON rewards.`coin_ids` = coin_owners.coin_id
AND coin_owners.`ownership_mode` =  'Reward'
AND STATUS =  '0'
) WHERE coins.id ='".validString($_REQUEST["coinId"])."' LIMIT 0,1
4

2 回答 2

4

非常感谢......但我使用了以下查询,它工作正常>---->

SELECT * , coins.id AS CoinId FROM coins

LEFT JOIN coin_owners ON coin_owners.coin_id = coins.id

LEFT JOIN transfer_detail ON transfer_detail.coin_id = coin_owners.coin_id AND transfer_detail.transfer_to = coin_owners.current_owner AND transfer_detail.transfer_from = SUBSTRING_INDEX( coin_owners.previous_owner,  ',',  '-1' ) AND coin_owners.`ownership_mode` =  'transfer'
LEFT JOIN rewards ON rewards.`coin_ids` = coin_owners.coin_id  AND coin_owners.`ownership_mode` =  'Reward' AND STATUS =  '0'

WHERE coins.id ='".mysql_real_escape_string(trim($_REQUEST["coinId"]))."' LIMIT 0,1 

感谢大家的帮助

于 2013-05-13T12:14:32.187 回答
1

CASE是一个表达式,你不能在表引用中使用它。您必须使用单独的查询来处理这两种情况,然后您可以使用以下方式组合UNION

(
  SELECT …
  FROM coins
  LEFT JOIN coin_owners ON coin_owners.coin_id = coins.id
  LEFT JOIN transfer_detail
    ON transfer_detail.transfer_to = coin_owners.current_owner
    AND transfer_detail.transfer_from =
        SUBSTRING_INDEX(coin_owners.previous_owner, ',', '-1')
  WHERE coin_owners.ownership_mode = 'transfer'
  AND coins.id = ?
UNION ALL
  SELECT …
  FROM coins
  LEFT JOIN coin_owners ON coin_owners.coin_id = coins.id
  LEFT JOIN rewards
    ON rewards.coin_ids = coin_owners.coin_id
    AND STATUS =  '0'
  WHERE coin_owners.ownership_mode = 'Reward'
  AND coins.id = ?
)
LIMIT 0,1

您必须确保两个查询的列匹配,可能通过将NULL值插入其中一个查询中没有对应值的列。

另请注意,除非您绝对确定传递的值对 SQL 注入是安全的,否则不应将请求参数以您所做的方式插入到字符串中。最好使用准备好的语句,这就是我?在查询中替换的原因。

于 2013-05-10T14:39:37.320 回答