MySQL 查询和连接

标签 mysql sql database join

我有两张 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/

相关文章:

mysql - 错误代码 : 1215. 无法添加外键约束

sql - 对两列使用 IN 运算符

database - 更改日志/审计数据库表的最佳设计?

sql - 在多对一表中使用哪个外键

mysql - sql 中 where 子句中 url 的一部分

mysql - 表 'performance_schema.session_variables' 不存在

SQL - 简单的 'OR' 不起作用!

sql - 检索分层组...无限递归

sql - 如何在golang中使用命令执行sql文件

php - MySQLi 准备好的语句未采用调用过程的有效查询