0

我有一个具有以下结构的表,

+-----------------------+------------------+------+-----+---------+----------------+
| Field                 | Type             | Null | Key | Default | Extra          |
+-----------------------+------------------+------+-----+---------+----------------+
| location_id           | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name                  | varchar(60)      | NO   |     | NULL    |                |
| city_id               | int(10) unsigned | NO   | MUL | NULL    |                |
| parent_location_id    | int(11)          | NO   |     | NULL    |                |
+-----------------------+------------------+------+-----+---------+----------------+

这里一个位置可能有也可能没有 parent_location_id,它是同一张表中的另一行。

现在我想选择所有至少有一个子位置的位置。我有以下查询。这是对的吗?

SELECT DISTINCT (
   a.location_id
), a.name, a.is_delivery_available, a.is_booking_available
FROM  `locations` a
JOIN  `locations` b ON a.location_id = b.parent_location_id
WHERE a.`city_id` =5
ORDER BY a.name ASC 
4

1 回答 1

0

使用LEFT JOIN而不是INNER JOIN

SELECT  a.location_id
        a.name, 
        a.is_delivery_available, 
        a.is_booking_available
FROM   `locations` a
            LEFT JOIN  `locations` b 
                ON a.location_id = b.parent_location_id
WHERE a.`city_id` = 5
ORDER BY a.name ASC
于 2012-08-07T04:15:48.517 回答