如何在PHP MYSQL中关联两列

时间:2015-06-26 09:17:33

标签: php mysql relate

我创建了一个包含所有请求信息的请求表。

包含以下列的表:

requestid , itemrequest1, itemrequest2, itemrequest3, quantity1, quantity2, quantity3

如何建立关系,以便如果itemrequestitemrequest2列中有值,则会从列quantity2中获取数量。

我的查询是这样的:

$query2=mysql_query("select * from tbl_request WHERE unit='$unit' AND  (itemrequest1='$itemrequest' or itemrequest2='$itemrequest' or  itemrequest3='$itemrequest')");
$record_num=mysql_num_rows($query2);

while ($data1 = mysql_fetch_array($query2))

问题是当$itemrequestitemrequest3中有值时,数量将始终显示第1列的数量。

1 个答案:

答案 0 :(得分:1)

You can use conditions in your query in order to select the right column depending on another column's value.

SELECT requestid, 
    (CASE WHEN itemrequest1 = '$itemrequest' THEN quantity1
        ELSE (
            CASE WHEN itemrequest2 = '$itemrequest' THEN quantity2
            ELSE (
                CASE WHEN itemrequest3 = '$itemrequest' THEN quantity3
            END)
        END)
    END)
FROM tbl_request

You should have a close look to your database structure though, if you have to do things like this, it might be better to improve your structure and have better tables/fields.