如果是MySQL中的CASE语句

时间:2014-03-22 06:55:29

标签: php mysql if-statement case

我试图在mqsql中使用if或case语句....这里是我的查询

$db->query("SELECT 
keywords.keyword,
keywords.keyid,
sources.s_title,
sources.s_disc,
sources.sourceid,
sources.s_link
FROM link_ks
INNER JOIN keywords ON link_ks.keyid = keywords.keyid
INNER JOIN sources ON link_ks.sourceid = sources.sourceid
case when 
thumbsup_items.votes_up+thumbsup_items.votes_down != ''
then 
INNER JOIN thumbsup_items ON link_ks.sourceid = thumbsup_items.name
 else null
WHERE link_ks.keyid = :keyid
 order by 
if((thumbsup_items.votes_up+thumbsup_items.votes_down) != '',
((thumbsup_items.votes_up+thumbsup_items.votes_down) desc ,thumbsup_items.votes_up desc,sources.sourceid),
sources.sourceid )
");

我使用了CASE,如果两者都是这个查询但没有任何工作我知道CASE和IF都给出了错误,但我不知道如何解决这个问题...

ERROR

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

修改的  我的问题是这个。如果没有投票,这个查询不提供任何输出,所以我使用IF语句

$db->query("SELECT 
keywords.keyword,
keywords.keyid,
sources.s_title,
sources.s_disc,
sources.sourceid,
sources.s_link
FROM link_ks
INNER JOIN keywords ON link_ks.keyid = keywords.keyid
INNER JOIN sources ON link_ks.sourceid = sources.sourceid
LEFT JOIN thumbsup_items ON thumbsup_items.votes_up+thumbsup_items.votes_down != '' AND link_ks.sourceid = thumbsup_items.name
WHERE link_ks.keyid = :keyid 
if((thumbsup_items.votes_up+thumbsup_items.votes_down) != '',
(thumbsup_items.votes_up+thumbsup_items.votes_down) desc ,
sources.sourceid )
");

If语句中出现错误... 请帮忙

2 个答案:

答案 0 :(得分:1)

将案例移到连接条件中,试试这个:

SELECT 
keywords.keyword,
keywords.keyid,
sources.s_title,
sources.s_disc,
sources.sourceid,
sources.s_link
FROM link_ks
INNER JOIN keywords ON link_ks.keyid = keywords.keyid
INNER JOIN sources ON link_ks.sourceid = sources.sourceid
LEFT JOIN thumbsup_items ON thumbsup_items.votes_up+thumbsup_items.votes_down != '' AND link_ks.sourceid = thumbsup_items.name
WHERE link_ks.keyid = :keyid
ORDER BY 
CASE
    WHEN (thumbsup_items.votes_up+thumbsup_items.votes_down) != ''
    THEN (thumbsup_items.votes_up+thumbsup_items.votes_down)
    ELSE sources.sourceid
END DESC

答案 1 :(得分:0)

您无法使用caseif来决定是否包含join。而是使用其他连接和结果集运行查询的其余部分,使用筛选条件获得所需结果。

SELECT语句中,IFCASE只能在列或表达式上加入表或视图后使用。但是你不能用

之类的条件构造语句
JOIN (CASE WHEN condition THEN this ELSE that END)