当另一列等于给定值时,SQL从列中选择值

时间:2013-03-06 16:43:52

标签: php sql sqlite

我有一个名为payment的表格,其中包含以下列: - bill IDgroup IDu1u1paidu2u2paidu3u3paidu4u4paidu5u5paid。我想要做的是存储其中一个付费列的值,如果我当前设置的userID等于存储在我选择的行中的一列u1,u2 ......等中的ID

示例,如果当前用户ID 等于u3中存储的ID,我想将u3paid的值存储在PHP变量中。实现此目的的SQL命令是什么?

尝试解决方案:

SELECT u1paid if u1 = SessionID or u2paid if u2 = SessionID or 
u3paid if u3 = SessionID or u4paid if u4 = SessionID or 
u5paid if u5 = SessionID FROM payment WHERE billID = BILLID;

我知道这不是正确的语法,但它是我能接近类似SQL的东西。

第二次编辑(基于两个马的回答):

$payment = "SELECT CASE WHEN u1 = '".$_SESSION['ID']."' THEN u1paid WHEN u2 = 
'".$_SESSION['ID']."' THEN u2paid WHEN u3 = '".$_SESSION['ID']."' THEN u3paid 
 WHEN u4 = '".$_SESSION['ID']."' THEN u4paid 
 WHEN u5 = '".$_SESSION['ID']."' THEN u5paid END AS PAID 
 FROM payment WHERE trackbill = '".$row['BID']."';"

之后,我试图通过$ payment ['PAID']来访问此语句中的值,但它仍然无效。我还在弄乱这件事吗?

Edit3:上面的命令有效,我刚搞砸了其中一个变量名:P

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT  CASE WHEN u1 = SessionID THEN u1paid 
             WHEN u2 = SessionID THEN u2paid
             WHEN u3 = SessionID THEN u3paid
             WHEN u4 = SessionID THEN u4paid
             WHEN u5 = SessionID THEN u5paid
             ELSE 'No result found'
        END AS Paid
FROM    payment 
WHERE   billID = BILLID;