MYSQL基于另一个表选择查询多个值

时间:2017-11-13 11:09:43

标签: php mysql laravel

我有两个表用于单位,一个表用于设施

Table units
+---------+---------------------+---------------------+-----------+----------+
| unit_id |     date added      |     date modified   | unit name |   user   |
+---------+---------------------+---------------------+-----------+----------+
|       1 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 |  Villa 1  | Smith    |
|       2 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 |  Villa 2  | Smith    |
|       3 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 |  Villa 3  | Jones    |
|       4 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 | Apartment | Smith    |
+---------+---------------------+---------------------+-----------+----------+

Table Amenities       
+---------+-----------+-------------------+
|      id |  Unit_id  |   Amenity         |
+---------+-----------+-------------------+
|       1 |         1 |   Air conditions  |
|       2 |         1 |   Internet        |
|       3 |         1 |   Water heaters   |
|       4 |         1 |   TV              |
|       5 |         2 |   TV              |
|       6 |         2 |   pool            |
|       7 |         2 |   Internet        |
|       8 |         3 |   Internet        |
|       9 |         4 |   Internet        |
+---------+-----------+-------------------+

我想选择有电视和互联网的单位

我试试

select units.* from units left join Amenities  on units.unit_id=Amenities.Unit_id  

where Amenities.Amenity='TV' and  Amenities.Amenity='Internet'

但没有工作

2 个答案:

答案 0 :(得分:1)

DROP TABLE IF EXISTS amenities;

CREATE TABLE amenities
(unit_id INT NOT NULL
,amenity VARCHAR(50) NOT NULL
,PRIMARY KEY(unit_id,amenity)
);

INSERT INTO amenities VALUES
(1,'Air conditions'),
(1,'Internet'),
(1,'Water heaters'),
(1,'TV'),
(2,'TV'),
(2,'pool'),
(2,'Internet'),
(3,'Internet'),
(4,'Internet');

SELECT unit_id 
  FROM amenities 
 WHERE amenity IN ('TV','Internet') 
 GROUP 
    BY unit_id 
HAVING COUNT(*) = 2;
+---------+
| unit_id |
+---------+
|       1 |
|       2 |
+---------+

显然,你永远不会有像你描述的那样的桌子。相反,你有一张单位表,一张设施表和一张表,说明哪个设施属于哪个单位。

答案 1 :(得分:0)

SELECT ua.*
FROM units AS ua
INNER JOIN units AS ub ON ua.unit_id = ub.unit_id
INNER JOIN Amenities AS aa
    ON ua.unit_id = aa.Unit_id
    AND aa.Amenity = 'TV'
INNER JOIN Amenities AS ab
    ON ub.unit_id = ab.Unit_id
    AND ab.Amenity = 'Internet';

以下是您的数据生成的输出:

+---------+---------------------+---------------------+-----------+-------+
| unit_id | date added          | date modified       | unit name | user  |
+---------+---------------------+---------------------+-----------+-------+
|       1 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 | Villa 1   | Smith |
|       2 | 2001-10-29 13:11:00 | 2001-10-29 13:11:00 | Villa 2   | Smith |
+---------+---------------------+---------------------+-----------+-------+