SQL的自定义变量用法(适用于navicat对接的mysql)

标题SQL的自定义变量用法(适用于navicat对接的mysql)

** 注意SET @变量 用法只支持原生mysql,因为navicat链接的mysql不支持回传服务器,如果一定要用,可以使用python+pymysql注入sql语句**

基本用法:

直接定义一列值

SELECT @x := 1, @y := 2

sql自定义变量

循环递增

此种用法可以在mysql中进行模拟排序,原理是:新定义一个变量列,强制链接到查询的表中,再查询时定义的变量不断让自己+1递增即可,这里+任何数都可以,可以根据实际情况做很多变化性操作。

SELECT
	@x := @x+1,
	amount
FROM 2019order
INNER JOIN (SELECT @x := 0) as tb1 ON 1=1

MySQL自定义变量递增

统一传入参数

对于复杂的sql查询,可能需要在各种连表或子查询中传入相同参数,参数可能需要调节,此时可以通自定义变量一次传入,比如下面这次RFM模型数据查询,最后一次传入@date参数

SELECT
	R.user_id,
	R.Rencency,
	F.Frequency,
	M.Monetary 
FROM
	(
	SELECT
		user_id,
		DATEDIFF( R1.Rencency, @date ) AS Rencency 
	FROM
		(
		SELECT
			user_id,
			MAX( create_time ) AS Rencency 
		FROM
			`order` 
		WHERE
			`status` = 2 
			AND platform_id IN { platformid } 
			AND create_time BETWEEN DATE_SUB( @date, INTERVAL 365 DAY ) AND @date 
		GROUP BY
			user_id 
		ORDER BY
			Rencency DESC 
		) AS R1 
	) AS R
	LEFT JOIN (
	SELECT
		user_id,
		F1.Frequency 
	FROM
		(
		SELECT
			user_id,
			COUNT(
			DISTINCT LEFT ( create_time, 7 )) AS Frequency 
		FROM
			`order` 
		WHERE
			`status` = 2 
			AND platform_id IN { platformid } 
			AND create_time BETWEEN DATE_SUB( @date, INTERVAL 365 DAY ) AND @date 
		GROUP BY
			user_id 
		ORDER BY
			Frequency 
		) AS F1 
	) AS F ON R.user_id = F.user_id
	LEFT JOIN (
	SELECT
		user_id,
		M1.Monetary 
	FROM
		(
		SELECT
			user_id,
			SUM( original_price / 100 ) AS Monetary 
		FROM
			`order` 
		WHERE
			`status` = 2 
			AND platform_id IN { platformid } 
			AND create_time BETWEEN DATE_SUB( @date, INTERVAL 365 DAY ) AND @date 
		GROUP BY
			user_id 
		ORDER BY
			Monetary 
		) AS M1 
	) AS M ON R.user_id = M.user_id
	INNER JOIN ( SELECT @date := '{date}' ) AS date_x ON 1 =1
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值