按表通过联合表排序

时间:2017-11-14 06:42:46

标签: mysql sql database

我的mySQL(双关语)有点生疏。我正试图通过另一张桌子加入一张桌子。

carparks has many clients
clients has many cars

这是查询

select `carparks`.* from `carparks`

left join `clients` on `carparks`.`carpark_id` = `clients`.`carpark_id` 

left join `cars` on `clients`.`client_id` = `cars`.`client_id` 

where `carparks`.`carpark_id` in (1, 3, 8, 33, 34, 38, 39) 

order by `cars`.`created_at` desc

正如你所看到我试图通过汽车的created_at列进行订购,上述查询虽然为停车场内的每​​辆车返回了重复的停车场。

我所看到的只是返回带有WHERE IN子句中的ID的停车场,只需按汽车表的created_at列排序。

由于

3 个答案:

答案 0 :(得分:4)

您可以在汽车表的最大创建日期

中的order by子句中使用聚合
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div id="sidebar">
  <!-- LOGO ROW -->
  <div class="row">
      <div class="col-12 logo"></div>
  </div>
  <!-- RESULTS ROW -->
  <div class="row">
    <div class="col-12 sidebar-content">
        <ul id="sidebar-results">
          <li>Result 1</li>
          <li>Result 2</li>
          <li>Result 3</li>
          <li>Result 4</li>
          <li>Result 5</li>
          <li>Result 6</li>
          <li>Result 7</li>
          <li>Result 8</li>
        </ul>
    </div>
  </div> 
</div>

答案 1 :(得分:0)

在返回停车场之前,将每个停车场的通缉日期减少到一个。请注意,如果停车场确实没有汽车而不是左连接是合乎逻辑的,但是我希望每个停车场(营业时间都开放)都会有汽车,因此可能不需要左连接。

SELECT `carparks`.*
FROM `carparks`
LEFT JOIN (
       SELECT
              `carparks`.`carpark_id`
            , max(`cars`.`created_at`) max_car_created
       FROM `clients`
       INNER JOIN `cars` ON `clients`.`client_id` = `cars`.`client_id`
       GROUP BY 
              `carparks`.`carpark_id`
       ) d ON `carparks`.`carpark_id` = d.`carpark_id`
WHERE `carparks`.`carpark_id` IN (1, 3, 8, 33, 34, 38, 39)
ORDER BY max_car_created DESC

答案 2 :(得分:0)

在进行连接之前减少停车场和客户端的数量,这将减少查询的执行时间。

SELECT A.* FROM (SELECT * FROM `carparks` WHERE `carpark_id` in
(1, 3, 8, 33, 34, 38, 39)) A LEFT JOIN
(SELECT `carpark_id`, `client_id` FROM `clients` WHERE `carpark_id` 
in (1, 3, 8, 33, 34, 38, 39)) B ON A.`carpark_id`=B.`carpark_id` LEFT JOIN
`cars` C ON B.`client_id` = C.`client_id`
GROUP BY A.`carpark_id`
ORDER BY MAX(C.`created_at`) DESC