从此查询中的另一个表中获取值

时间:2016-04-28 09:05:01

标签: mysql sql

此查询运行良好,但问题是我需要获取另一个名为rooms的表中的房间号。下面的查询从reservations表中获取了只有room_id的数据:

$select_table = "SELECT id, name, phone, email, address, country, adults, childs, purpose, booking_type, remarks, checkin, checkout, room_id, status, paid, date FROM reservations WHERE DATE_FORMAT(date, '%Y-%m') = '$date' ORDER BY id DESC";
$stmt = $db->prepare($select_table);
$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_ASSOC);
if ($rows)
{
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = $stmt->fetch(PDO::FETCH_ASSOC);
}

我如何从number表中获取上述查询中的列rooms

3 个答案:

答案 0 :(得分:2)

Join房间的桌子!

SELECT r.id, r.name, r.phone, r.email, r.address, r.country, r.adults, r.childs, r.purpose,
       r.booking_type, r.remarks, r.checkin, r.checkout, r.room_id, r.status, r.paid, r.date,
       rooms.number  
FROM reservations r
JOIN rooms ON r.room_id = rooms.id
WHERE DATE_FORMAT(r.date, '%Y-%m') = '$date'
ORDER BY r.id DESC

(我厌倦了一遍又一遍地输入reservations,所以我为该表创建了一个表别名r。)

答案 1 :(得分:0)

通过加入两个表来更改查询以包含房间号:

  $query =  "SELECT id, name, phone, email, address, country, adults, childs, purpose, booking_type, remarks, checkin, checkout, room_id, status, paid, date , ro.number AS number FROM reservations AS r JOIN rooms AS ro ON r.room_id=ro.id WHERE DATE_FORMAT(date, '%Y-%m') = '$date' ORDER BY id DESC";

假设rooms表有id字段且reservation.room_id是引用rooms.id的外键,则查询将起作用。

答案 2 :(得分:0)

你能试试吗

    SELECT rooms.number, reservations.id, name, phone, email, address, country, 
    adults, childs, purpose, booking_type, remarks, checkin, checkout, room_id, 
    status, paid, date FROM reservations left join rooms on reservations. room_id =rooms.id 
WHERE DATE_FORMAT(date, '%Y-%m') = '$date' ORDER BY id DESC