期待这很简单,我错过了一些明显的东西。
我有2张桌子。
汽车:
CarID, dealerID, info1, info2, info3
查询:
enqID, carID, dealerID, info1, info2, info3
和1个要过滤的变量:
$_SESSION['dealerID']
查询是针对某人提交的汽车的报价,以及他们的电子邮件和价格等。
我需要在一个查询中获取汽车的详细信息和查询/优惠的详细信息。 因此,选择经销商ID =会话然后相同的汽车,但基于他们的结果。
我试过了:
$query = $db->query
("SELECT *
FROM cars, enquiries
WHERE cars.dealerID = ".$_SESSION['dealerID']."
AND enquiries.dealerID = ".$_SESSION['dealerID']."");
但这只会返回所有配有匹配的dealerID作为会话的汽车。
我需要在数组中执行1次查询和if循环吗?所以查询从经销商处获取所有汽车,然后循环每个$ row ['dealerID'],直到我在查询中找到与dealerID的匹配?
答案 0 :(得分:2)
我不确定我是否理解你,但试试这个
SELECT *
FROM cars INNER JOIN enquiries
ON cars.CarID=enquiries.carID
WHERE cars.dealerID = '".$_SESSION['dealerID']."'";
答案 1 :(得分:1)
首先,注意SQL注入,你的代码不安全。首选使用预备声明(http://www.php.net/pdo.prepared-statements)
对于您的查询,您需要定义使用星号
的列SELECT cars.*, enquiries.*
FROM cars, enquiries
WHERE ( cars.dealerID = ? AND enquiries.dealerID = ? );
或更准确地说不重复carId
SELECT cars.carID, cars.dealerID, cars.info1, cars.info2, cars.info3, enquiries.enqID, enquiries.dealerID, enquiries.info1, enquiries.info2, enquiries.info3
FROM cars, enquiries
WHERE ( cars.dealerID = ? and enquiries.dealerID = ? );
答案 2 :(得分:0)
您需要在正确的连接键上加入表。我相信在这种情况下CarId
是正确的密钥:
SELECT *
FROM cars c join
enquiries e
ON e.CarId = c.CarId
WHERE c.dealerID = ".$_SESSION['dealerID']." AND
e.dealerID = ".$_SESSION['dealerID']
答案 3 :(得分:0)
如果要从两个表中都带有条件的表中获取数据,则需要连接表: -
SELECT *
FROM cars left join
enquiries ON enquiries.CarId = cars.CarId
WHERE cars.dealerID = ".$_SESSION['dealerID']."
AND
enquiries.dealerID = ".$_SESSION['dealerID']