经典子查询:
select t.* from (select * from ec_order_item) t where t.order_id in (select id from ec_order where user_id=2)
select
t1.PROFIT_TYPE as PROFIT_TYPE,
(select d.DICT_NAME
from TB_PC_DICT d
where t1.PROFIT_TYPE = d.DICT_ID
and d.DICT_TYPEID = ‘UNITE_DS_PROFIT_TYPE‘) as NAME_OF_PROFIT_TYPE,
(select d.DICT_NAME
from TB_PC_DICT d
where t2.OBJ_CLASS = d.DICT_ID
and d.DICT_TYPEID = ‘GD_OBJ_CLASS‘) as CATENTRY_TYPE,
(select d.DICT_NAME
from TB_PC_DICT d
where t1.STATE = d.DICT_ID
and d.DICT_TYPEID = ‘UNITE_DS_STATUS_OTHER‘) as NAME_OF_STATE,
(select SUM(t3.num)
from TB_GD_STOCK t3
where t3.goods_id = t1.goods_id) as QUANTITY,
(select MAX_PRICE
from TB_GD_PRICE t3
where t3.goods_id = t1.goods_id
and t3.PRICE_TYPE = ‘SELLING‘
and t3.ISDEFAULT = ‘1‘) as PRICE,
(select SUM(1)
from TB_UNITE_DS_DISTRIBUTOR_ORDER t3
where t3.goods_id = t1.goods_id) as SEND_NUM
from (select g.rela_id,
from TB_UNITE_DS_GOODS g
left join (select r.rela_id RELA_ID,
r.start_date,
from TB_UNITE_DS_PROFIT_RULE r,
TB_UNITE_DS_GOODS_PROFIT p
where r.rule_id = p.rule_id
and r.start_date <= sysdate
and r.end_date >= sysdate) b -- b是处于有效期内的分成信息
on g.rela_id = b.rela_id --分销商品跟分成信息关联
WHERE (g.distributor_id = 61)) t1, --过滤出分销商id是61的,将分销商品与分成信息连接为t1
TB_GD_GOODS t2
where t1.goods_id = t2.GOODS_ID --跟商品表关联
ORDER BY catentry_Id asc
LEFT JOIN 关键字会从左表 (Persons) 那里返回所有的行,即使在右表 (Orders) 中没有匹配的行。
另外,查出的总数量,跟左表与右表的数量,没有必然的关系,左表数量很少,右表数量多的时候,查出的结果会比右表的数量还要多,没搞懂原因。
select * from TB_UNITE_DS_GOODS g
left join ( select * from tb_1 ) b
on g.rela_Id = b.rela_id
where g.xxId = xx
分析:left join后面的查询结果是附加的,只有TB_UNITE_DS_GOODS 表会展示全部的信息。
如何取SQL结果集的第一条记录
在SQL Server数据库中,使用top关键字:
SELECT TOP number|percent column_name(s) FROM table_name
在MySQL数据库中,使用LIMIT关键字:
SELECT column_name(s) FROM table_name LIMIT number
例子:SELECT * FROM Persons LIMIT 1
在Oracle数据库中,使用ROWNUM关键字:
SELECT column_name(s) FROM table_name WHERE ROWNUM <= number
例子:SELECT * FROM Persons WHERE ROWNUM <= 1
MYSQL一对多查询
SELECT (SELECT GROUP_CONCAT(tag_name) FROM tb_gh_tag t WHERE t.TAG_ID IN (SELECT m.TAG_ID FROM tb_gh_TAG_mid m WHERE m.OBJ_ID = m2.COURSE_ID AND m.type=0)) TAG_NAMES,m2.* FROM tb_gh_course m2
原文:http://hebinteng.blog.51cto.com/7967512/1974931