search

Home  >  Q&A  >  body text

MySQL multi-expression if statement

I want to execute multiple expressions in an if statement within a select statement like this:

SELECT 
  t.id,
  IF (
    id > 10,
    @var1 := t.id; @var2 := t.title,
    t.title
  )
FROM
  table

Is there a way to execute these two expressions @var1 := t.id; @var2 := t.title in one if statement?

P粉748218846P粉748218846463 days ago706

reply all(1)I'll reply

  • P粉674876385

    P粉6748763852023-09-20 09:12:51

    You can do this

    SELECT
      t.id,
      IF (
        id > 10,
        CONCAT(@var1 := t.id , @var2 := t.title),
    
        t.title
      )
    FROM
      table1 t;
    SELECT @var2;
    SELECT @var1;

    But user-defined variables are scalar values, so you can only get the last value of @var1 and @var2 that were selected, but it will not display the connected value now.

    So overall, this doesn't really make sense if you have multiple rows of data.

    reply
    0
  • Cancelreply