在mysql查询中使用IF条件

时间:2017-08-22 02:47:57

标签: php mysql

您好我正在尝试根据另一个表的值加入该表。在我的方案中,我希望在job是其他人加入表message.type时加入表post_ads。我写了下面的MySql查询,但它的抛出语法错误。请帮忙。

 SELECT message.*,register.name, rg.name as to_user_name, post_ads.*
 FROM message 
 INNER JOIN register ON message.from_user_id = register.id 
 INNER JOIN register rg ON message.to_user_id = rg.id LEFT JOIN 

 CASE message.type WHEN 'job' THEN 

 SELECT 'job.title' as titles FROM job 
 WHERE (message.`from_user_id` = '196' AND message.`to_user_id` = '218') OR 
 (message.`from_user_id` = '218' AND message.`to_user_id` = '196')

  ELSE

  SELECT 'post_ads.brand_category, post_ads.model_category, post_ads.titles, 
  post_ads.images, post_ads.ads_main_pic'  FROM post_ads  
  WHERE (message.`from_user_id` = '196' AND message.`to_user_id` = '218') OR 
  (message.`from_user_id` = '218' AND message.`to_user_id` = '196')

  END as post_ads

2 个答案:

答案 0 :(得分:3)

首先,您滥用了案例陈述。它应该在select语句中不在左连接中。 2,当我们使用case语句时,你不能选择多个字段。 - 要解决此问题,您可以将CONCAT函数与用户定义的contastant一起使用,并在服务器端脚本中进行操作。

您应该编写类似下面的查询

SELECT message.*,register.name, rg.name AS to_user_name, post_ads.*,

CASE `message`.`type` WHEN 'job' THEN 

(SELECT job.title  FROM job 
WHERE (message.`from_user_id` = '196' AND message.`to_user_id` = '218') OR 
(message.`from_user_id` = '218' AND message.`to_user_id` = '196')) 

ELSE

(SELECT  post_ads.titles FROM post_ads  
WHERE (message.`from_user_id` = '196' AND message.`to_user_id` = '218') OR 
(message.`from_user_id` = '218' AND message.`to_user_id` = '196'))

END AS post_ads

FROM message 
INNER JOIN register ON message.from_user_id = register.id 
INNER JOIN register rg ON message.to_user_id = rg.id 

答案 1 :(得分:1)

尝试这样的事情:



$query = ("select * from `table1` where (`param`='$param' AND `$param2 `='$param2') OR `param3`='$param3");




修改它以适合您的查询。

修改

再次通过你的代码,我认为你错过了括号:



 SELECT message.*,register.name, rg.name as to_user_name, post_ads.*
 FROM message 
 INNER JOIN register ON message.from_user_id = register.id 
 INNER JOIN register rg ON message.to_user_id = rg.id LEFT JOIN 

 CASE message.type WHEN 'job' THEN 

 SELECT 'job.title' as titles FROM job 
 WHERE ((message.`from_user_id` = '196' AND message.`to_user_id` = '218') OR 
 (message.`from_user_id` = '218' AND message.`to_user_id` = '196'))

  ELSE

  SELECT 'post_ads.brand_category, post_ads.model_category, post_ads.titles, 
  post_ads.images, post_ads.ads_main_pic'  FROM post_ads  
  WHERE( (message.`from_user_id` = '196' AND message.`to_user_id` = '218') OR 
  (message.`from_user_id` = '218' AND message.`to_user_id` = '196'))

  END as post_ads