Mysql多表查询,取出其中一张表的最大的数据或者去重的字段

需求:1、查询三张表共同存在的数据(本来用的内连接)
2、后来要求再加一张表,把这张表的最大数据查出来合到一起(外键管理订单号)

SELECT 
	@ROW := @ROW + 1 AS DT_RowId,
  tzo.order_id,
  tzo.order_num,
	tzu.user_phone,
	FROM_UNIXTIME(tzv.creat_time , '%Y-%m-%d' ) AS creat_time
FROM
( SELECT @ROW := 0 ) t,
	t_zebra_order tzo,
	t_zebra_user tzu,
	t_zebra_vehiclereport tzv	
	WHERE
	tzo.user_id = tzu.user_id 
	AND tzo.order_num = tzv.order_num	

上面为以前的需求,现在分析后面的需求
(1)先查出最大数据

SELECT max(follow_id) FROM t_zebra_follow GROUP BY follow_order_num

(2)再查出此表所有信息(把第一步作为子查询)

SELECT * FROM t_zebra_follow WHERE follow_id in (SELECT max(follow_id) FROM t_zebra_follow GROUP BY follow_order_num)

最后和以前的需求合并到一起,我用左连接,因为(左边多表查询出来的数据,一个订单号对应新表多条数据或者0条数据)

SELECT
	@ROW := @ROW + 1 AS DT_RowId,
	tzo.order_id,
	tzo.order_num,
	tzu.user_phone,
	FROM_UNIXTIME( tzv.creat_time, '%Y-%m-%d' ) AS creat_time,
	t1.follow_up,
	t1.follow_person 
FROM
	( SELECT @ROW := 0 ) t,
	t_zebra_order tzo,
	t_zebra_user tzu,
	t_zebra_vehiclereport tzv
	LEFT JOIN ( SELECT * FROM t_zebra_follow WHERE follow_id IN ( SELECT max( follow_id ) FROM t_zebra_follow GROUP BY follow_order_num ) ) t1 ON tzv.order_num = t1.follow_order_num 
WHERE
	tzo.user_id = tzu.user_id 
	AND tzo.order_num = tzv.order_num

你可能感兴趣的:(数据库)