[英]In MySQL 5.7 how would I select all parent table rows with less than 2 related child table rows
Again this is a MySQL 5.7 DB. 同样,这是一个MySQL 5.7 DB。 For example, let's say I have a database for a car lot, a table for cars and a table for price updates.
例如,假设我有一个汽车数据库,一个汽车表和一个价格更新表。 (This is a contrived example).
(这是一个人为的示例)。
Database: CarLot
Table: Cars
-Id
-Year
-Make
-Model
Table: PriceUpdates
-Id
-CarId (FK Cars:Id)
-Price
-DateChanged
To pseudo code what I want to do would look like: 伪代码我想做的事情看起来像:
SELECT * from Cars WHERE a Car has < 2 PriceUpdate rows (for each given CarId there are less than 2 associated PriceUpdate rows) 在汽车有<2个PriceUpdate行的情况下从汽车中选择*(对于每个给定的CarId,少于2个关联的PriceUpdate行)
I'm not super strong in SQL and not sure if it's doable in a simple query or if I have to get into a procedure or T-SQL or something. 我在SQL方面不是很强,也不确定在简单的查询中是否可行,或者是否必须进入过程或T-SQL之类。
A join query with an assertion on the count should work here: 带有断言的联接查询应该在这里工作:
SELECT c.*
FROM Cars c
LEFT JOIN PriceUpdates pu
ON c.Id = pu.CarId
GROUP BY
c.Id
HAVING
COUNT(pu.CarId) < 2;
Note: In MySQL (and ANSI SQL) it is completely valid to group by Cars.Id
and select all other columms from this table because these columns are functionally dependent on the Id
column. 注意:在MySQL(和ANSI SQL)中,按
Cars.Id
并从该表中选择所有其他列是完全有效的,因为这些列在功能上取决于Id
列。
If you wanted the prices as well (which seems likely despite your pseudo-code), then exists
would often be used: 如果您还想要价格(尽管您使用了伪代码,这似乎也是可能的),那么通常会使用
exists
:
SELECT c.*, pu.*
FROM Cars c LEFT JOIN
PriceUpdates pu
ON c.Id = pu.CarId
WHERE NOT EXISTS (SELECT 1
FROM PriceUpdates pu2
WHERE pu2.CarId = pu.CarId AND
pu2.Id <> pu.Id
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.