IF condition between Mysql PHP tables

Asked

Viewed 306 times

1

Opa,

I have two tables: forma_pagamento and forma_pagamento_selecionada.

I have a while where should be listed all forms of payment, so in this while should have a condition IFwhere will return me a new column, if, are found equal values between the two tables, example, that did not work.

SELECT
  *,
  IF(forma_pagamento_selecionado_id = forma_pagamento_id, NULL, 'checked') AS isChecked
FROM 
  forma_pagamento_selecionado
INNER JOIN
  forma_pagamento ON forma_pagamento_id = forma_pagamento_selecionado_id

That is, if the forma_pagamento_selecionado_id be equal to forma_pagamento_id, the isCheckd will receive the value 'checked', if not equal, will not receive value.

  • Cara gives a read on COALESCE Mysql, does not meet your needs? Because you test the conditions per parameter until you find one that is not null.

2 answers

3


The way you’re relating to INNER JOIN will always return the values where forma_pagamento_id is equal to forma_pagamento_selecionado_id, then the if there will be useless besides being declared incorrectly.

Since you want to list all results, equal or not, use the LEFT JOIN and the IF as follows:

SELECT forma_pagamento_selecionado.*, 
IF(forma_pagamento.ID IS NULL, 'NULL', 'Checked') AS isChecked
FROM forma_pagamento_selecionado
LEFT JOIN forma_pagamento 
ON forma_pagamento.ID = forma_pagamento_selecionado.ID

See working on SQL Fiddle

1

Solved, thanks to the idea of @Marcelo de Andrade

SELECT
      forma_pagamento_id,
      forma_pagamento_nome,
      forma_pagamento_selecionado_id,
      IF(forma_pagamento_selecionado_id IS NULL, 'NULL', '1') AS forma_pagamento_aceita
FROM
    forma_pagamento
LEFT JOIN
     forma_pagamento_selecionado ON forma_pagamento.forma_pagamento_id = forma_pagamento_selecionado.forma_pagamento_selecionado_id 
and
     forma_pagamento_selecionado_id = 1

Vlw

Browser other questions tagged

You are not signed in. Login or sign up in order to post.