php - MYSQL select query based on another tables 多个值

标签 php mysql laravel

我有两张 table ,一张用于单位,一张用于便利设施

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'

但不工作

最佳答案

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 |
+---------+

显然,您永远不会拥有一张与您描述的一样的 table 。取而代之的是,您会有一张单位表、一张便利设施表和一张说明哪个便利设施属于哪个单元的表格。

关于php - MYSQL select query based on another tables 多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47262921/

相关文章:

php - 使用PHP的关联数组的一行总和?

php - 带有随机添加其他图像区域的图像

php - Mysql触发器还是PHP编码?

mysql - 我如何构造在 MySQL 数据库中链接在一起的一堆项目?

php - 我可以将模型关联到 laravel 中的通知表吗?

php - 用php处理大文件到数据库

javascript - 通过javascript循环上传多个 Canvas 图像

php - Laravel 5.1 单页多表单命名消息包

mysql - 从结果中选择

laravel - 如何根据目标用户的角色将其重定向到不同的路线?