Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

Local variable inside mysql statement

I'm trying to figure out if it's possible to use a local varaible inside a mysql statement.

I've a statement that looks something like this (unrelated fields, joins and conditions have been filtered):

SELECT
  m.id,
  IF (!m.subscribers_only OR m.user_id = ? OR !ISNULL(mu.media_id) OR !ISNULL(us.user_id), 1, 0) AS has_access
FROM media m
LEFT JOIN media_user mu ON mu.user_id = ? AND m.id = mu.media_id
LEFT JOIN user_subscriptions us ON us.user_id = ? AND m.user_id = us.user_subscriber_to_id

All 3 variable is the same variable, so instead of having to bind the parameter 3 times, is it possible to set a local variable in the statement and only having to do 1 bind.

I've considered using SET @current_user = 1 and then using @current_user, but as I'm using PDO, it's not possible to run two statements in one query, and I'm worried how the interaction is when combined with a load balancer.

Edit to show how I'm printing @paramter_test:

SELECT
  m.id,
  @parameter_test,
  IF (!m.subscribers_only OR m.user_id = @parameter_test OR !ISNULL(mu.media_id) OR !ISNULL(us.user_id), 1, 0) AS has_access
  FROM media m
JOIN (SELECT @parameter_test:= 1) a
LEFT JOIN media_user mu ON mu.user_id = @parameter_test AND m.id = mu.media_id
LEFT JOIN user_subscriptions us ON us.user_id = @parameter_test AND m.user_id = us.user_subscriber_to_id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try something like:

SELECT
m.id,
IF (!m.subscribers_only OR m.user_id = @parameter_test OR !ISNULL(mu.media_id) OR 
!ISNULL(us.user_id), 1, 0) AS has_access
FROM media m
JOIN (SELECT @parameter_test:= 1) a
LEFT JOIN media_user mu ON mu.user_id = @parameter_test AND m.id = mu.media_id
LEFT JOIN user_subscriptions us ON us.user_id = @parameter_test AND m.user_id = 
us.user_subscriber_to_id

You can always create a variable inside a sql statement as long as it's declared before it's use.

In this case you won't be using placeholder ? since those are replaced by parameter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...