[英]Laravel select all rows if id exists in another table and a column has specific values on that table
[英]Select rows where a column has specific values with similar ID's
我需要編寫一個查詢,我需要返回具有相似 ID 的行,並且它們需要包含特定值。 在下面的示例中,有多個 ID 具有不同的 colors。
我需要 select 所有僅包含黃色、紅色和藍色的行。 所以這里 0 和 2 的 ID 將返回這些行,而 1 和 3 將不會返回,因為它不包含我需要的特定集合。 我還需要返回 ID 和 Colors。
ID | Colors |
---|---|
0 | 黃色 |
0 | 紅色的 |
0 | 藍色的 |
1 | 黃色 |
1 | 紅色的 |
2 | 黃色 |
2 | 紅色的 |
2 | 藍色的 |
3 | 紅色的 |
3 | 綠色的 |
3 | 藍色的 |
返回的數據應返回為
ID | Colors |
---|---|
0 | 黃色 |
0 | 紅色的 |
0 | 藍色的 |
2 | 黃色 |
2 | 紅色的 |
2 | 藍色的 |
我在這里嘗試過這樣做,但我假設它不會工作,因為它選擇了包含任何 colors 的行。 但它需要包含所有 colors。
SELECT `id` , `Colors` FROM Tbl WHERE COLORS IN ('Yellow','Red','Blue') GROUP BY `id` Order BY `ID`.
下次請與數據共享架構,它可以節省願意幫助您的其他人的時間。
請注意,這只會確保所有必需的值IN
子句都存在。
SELECT id, colors
FROM Test
WHERE id IN (
select id from Test
where colors in ('Yellow','Red', 'Blue')
group by id having count(1) = 3
)
樣本數據:
create table Test(id integer, colors varchar(10));
insert into Test(id, colors) values
(0, 'Yellow'), (0, 'Red'), (0, 'Blue'),
(1, 'Yellow'),(1, 'Red'),
(2, 'Yellow'),(2, 'Red'), (2,'Blue'),
(3, 'Red'), (3, 'Green'), (3, 'Blue') ;
SELECT * FROM Test WHERE id IN (select id from Test where colors in ('Yellow','Red', 'Blue') group by id having count(1) = 3) ;
試驗結果:
mysql> create database test;
Query OK, 1 row affected (0.00 sec)
mysql> use test;
Database changed
mysql> create table Test(id integer, colors varchar(10));
Query OK, 0 rows affected (0.04 sec)
mysql> insert into Test(id, colors) values
-> (0, 'Yellow'), (0, 'Red'), (0, 'Blue'),
-> (1, 'Yellow'),(1, 'Red'),
-> (2, 'Yellow'),(2, 'Red'), (2,'Blue'),
-> (3, 'Red'), (3, 'Green'), (3, 'Blue') ;
Query OK, 11 rows affected (0.01 sec)
Records: 11 Duplicates: 0 Warnings: 0
mysql> select * from Test;
+------+--------+
| id | colors |
+------+--------+
| 0 | Yellow |
| 0 | Red |
| 0 | Blue |
| 1 | Yellow |
| 1 | Red |
| 2 | Yellow |
| 2 | Red |
| 2 | Blue |
| 3 | Red |
| 3 | Green |
| 3 | Blue |
+------+--------+
11 rows in set (0.00 sec)
mysql> SELECT * FROM Test WHERE id IN (select id from Test where colors in ('Yellow','Red', 'Blue') group by id having count(1) = 3) ;
+------+--------+
| id | colors |
+------+--------+
| 0 | Yellow |
| 0 | Red |
| 0 | Blue |
| 2 | Yellow |
| 2 | Red |
| 2 | Blue |
+------+--------+
6 rows in set (0.00 sec)
mysql> -- For example for Green, Red, Blue
mysql> SELECT * FROM Test WHERE id IN (select id from Test where colors in ('Green','Red', 'Blue') group by id having count(1) = 3) ;
+------+--------+
| id | colors |
+------+--------+
| 3 | Red |
| 3 | Green |
| 3 | Blue |
+------+--------+
3 rows in set (0.00 sec)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.