联接和并集
示例
内连接:从“汽车”和“模型”中检索数据表:
SELECT c.ID, m.model FROM cars c INNER JOIN models m ON c.model = m.ID
并集: 合并两个查询的结果以获取所有跑车和 4WD:
SELECT c.ID, m.model FROM cars c INNER JOIN models m ON c.model = m.ID WHERE m.ID = 1 UNION SELECT c.ID, m.model FROM cars c INNER JOIN models m ON c.model = m.ID WHERE m.ID = 3
左外连接: 查找所有品牌及其汽车数量,包括没有任何品牌的品牌cars:
SELECT b.brand, COUNT(c.id) AS countOfBrand FROM brands b LEFT OUTER JOIN cars c ON b.ID = c.brand GROUP BY b.brand
相交: 仅检索“颜色”和“型号”表中相同的行:
SELECT m.model, c.color FROM models m INNER JOIN colors c ON m.ID = c.ID WHERE m.model = 'Sports' AND c.color = 'Red'
以上是如何使用 SQL 连接和联合高效地从多个表中检索数据?的详细内容。更多信息请关注PHP中文网其他相关文章!