6.1 表的加减法
集合运算注意事项
<1> 列的数量与类型要相互对应
<2>可以使用任何SELECT子句,但是ORDER BY子句只能在最后使用一次
表的加法 UNION(并集) --不包括重复行
SELECT
product_id,
product_name,
product_type
FROM
`product`
UNION
SELECT
id,
NAME,
type
FROM
pp2
表的加法 UNION ALL --包括重复行
SELECT
product_id,
product_name,
product_type
FROM
`product`
UNION ALL
SELECT
id,
NAME,
type
FROM
pp2
选取表中公共部分 INTERSECT --交集 Mysql不支持
记录的减法 EXCEPT --差集 Mysql不支持
6.2 联结(JOIN)
6.2.1 内联结(也就是取联结键/列的交集)
SELECT
USER .uid,
USER .uname,
USER .nickname,
verf. NAME,
verf. STATUS
FROM
u_user AS USER
INNER JOIN u_user_verify_record AS verf ON `USER`.uid = verf.uid
6.2.2 外联结
外联结分为左联结(LEFT JOIN)和右联结(RIGHT JOIN),就是以那边的表作为主表
-- 例:三表联合查询(左联结),mysql中OUTER可省略
SELECT
a.uname AS '用户ID',
a.phone AS '账号',
a.nationality AS '国家',
a.nickname AS '昵称',
b. STATUS AS '实名认证',
d.is_super_partner AS '超级伙伴',
a.growth_index AS '大师指数',
a.create_time AS '创建时间',
c.balance_assets AS '可用余额',
c.reserve AS '理财余额',
c.otc_assets AS 'OTC余额'
FROM
u_user a
LEFT OUTER JOIN u_user_verify_record b ON a.uid = b.uid
LEFT OUTER JOIN u_user_invite d ON a.uid = d.uid
LEFT OUTER JOIN a_user_account_asset c ON a.uid = c.uid
AND c.asset_name = 'USDC'
WHERE
a.uname != '10000'
右联结以此类推,不再举例
6.2.3 交叉联结
交叉联结的结果是笛卡尔集,一般不会用到
SELECT
USER .uid,
USER .uname,
USER .nickname,
verf. NAME,
verf. STATUS
FROM
u_user AS USER
CROSS JOIN u_user_verify_record AS verf
在mysql中后可加ON(联结键),作用相当于内联结INNER JOIN