SQL Select查询连接多个表

时间:2013-07-29 10:08:50

标签: php sql select left-join

我有这段代码:

function getPricing() {
$returnarr = array();
$dcid = (isset($_REQUEST['dcid'])) ? "WHERE datacentre_id='" . mysql_real_escape_string($_REQUEST['dcid']) . "'" : '';

$addons = $_REQUEST['addon'];

if ($addons == "true")
    $sql = "SELECT * FROM addonprices $dcid ORDER BY addon_desc ASC";
else
    $sql = "SELECT l.l_name, p.* FROM pricing p LEFT JOIN locations l ON l.location_id=p.datacentre_id $dcid ORDER BY CASE splitsize WHEN 'f' THEN 0 WHEN 'w' THEN 1 WHEN 'h' THEN 2 WHEN 'q' THEN 3 WHEN '2U' THEN 4 WHEN '1U' THEN 5 ELSE 6 END DESC, amps ASC";

$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    $returnarr[] = $row;
}
header('Content-type: application/json');
echo json_encode($returnarr);
}

我需要在两个select语句中添加另一个表,加入$dcid,该表名为slas,列为currency我尝试了一些但不是运气。

我正在尝试将货币拉入javascript文件以使用此switch语句获取价格:

var currency = "";

            switch (row.currency) {
                case '1' :
                    currency = "£";
                    break;
                case '2' :
                    currency = " $";
                    break;
                case '3' :
                    currency = "€";
                    break;
                default:
                    currency = "£";
                    break;


            }

即使货币应该等于2或3,它仍然显示为默认值...我不确定它是错误的switch语句还是sql查询。

更新

只是遇到这一行的问题:

$sql = "SELECT l.l_name, p.*, slas.currency FROM pricing p LEFT JOIN locations l ON l.location_id=p.datacentre_id LEFT JOIN slas ON slas.datacentre_id = p.datacentre_id $dcid ORDER BY CASE splitsize WHEN 'f' THEN 0 WHEN 'w' THEN 1 WHEN 'h' THEN 2 WHEN 'q' THEN 3 WHEN '2U' THEN 4 WHEN '1U' THEN 5 ELSE 6 END DESC, amps ASC";

取自以下答案。

1 个答案:

答案 0 :(得分:0)

我认为这里的问题是datacentre_id中的不合格WHERE将不允许您加入另一个名为datacentre_id

的列的表

我会建议WHERE是

$dcid = (isset($_REQUEST['dcid'])) ? "WHERE p.datacentre_id='" . mysql_real_escape_string($_REQUEST['dcid']) . "'" : '';

,查询为

if ($addons == "true")
    $sql = "SELECT p.*, slas.currency FROM addonprices p LEFT JOIN slas ON slas.datacentre_id = p.datacentre_id $dcid ORDER BY addon_desc ASC";
else
    $sql = "SELECT l.l_name, p.*, slas.currency FROM pricing p LEFT JOIN locations l ON l.location_id=p.datacentre_id LEFT JOIN slas ON slas.datacentre_id = p.datacentre_id $dcid ORDER BY CASE splitsize WHEN 'f' THEN 0 WHEN 'w' THEN 1 WHEN 'h' THEN 2 WHEN 'q' THEN 3 WHEN '2U' THEN 4 WHEN '1U' THEN 5 ELSE 6 END DESC, amps ASC";

请注意,在这两种情况下,datacentre_id中的表都是别名p