我有两张 table ..
devices(id, brand_id, device_name) brands(id, brand_name)
I have a number of brands that do not have a single device in the devices table, I basically want to ignore these brands that do not have at least 1 single device
Using the rows below how would I return the query to only all brands that have an entry in the devices table as they have entries in the devices (with brand_id being the foreign key in the devices table) - would this need a join?
e.g table structure
brands table:
id name
1 apple
2 samsung
3 acme
devices table:
id brand_id name
1 1 iphone
2 2 galaxy s4
3 1 ipad
# desired db result #
1 Apple
2 Samsung
最佳答案
INNER JOIN
可让您获取拥有设备的所有品牌。我们按品牌 ID 进行分组,这 sample 牌就不会为每台设备返回一次。
SELECT brands.*
FROM brands
INNER JOIN devices ON (brands.id = devices.brand_id)
GROUP BY brands.id
另一种方法是使用子查询,但我相信联接会更快:
SELECT *
FROM brands
WHERE id IN (SELECT brand_id FROM devices);
关于MySQL 查询和连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19404760/