0

I´m doing a query

SELECT ROUND((SUM(refracciones.total)+(serviciosrealizados.total)),2)
FROM refracciones, serviciosrealizados
WHERE refracciones.id_ticket = '$idticket' AND serviciosrealizados.id_ticket = '$idticket'

2 tables:

  1. refracciones
  2. serviciosrealizados

2 columns:

  1. refracciones.total
  2. serviciosrealizados.total

At the moment the query is working but just if I insert data in both table.

I will like the query show me the total of refracciones.total + serviciosrealizados.total if one of the field are empty show me the total with refracciones.total or serviciosrealizados.total

1
  • WARNING: Whenever possible use prepared statements to avoid injecting arbitrary data in your queries and creating SQL injection bugs. These are quite straightforward to do in mysqli and PDO where any user-supplied data is specified with a ? or :name indicator that’s later populated using bind_param or execute depending on which one you’re using. Commented Mar 2, 2017 at 1:15

1 Answer 1

1

If, say, id 5 is only in serviciosrealizados, this query should do what you want:

SELECT ROUND(SUM(IFNULL(r.total, 0)) + IFNULL(s.total, 0), 2)
FROM refracciones r
  LEFT OUTER JOIN serviciosrealizados s ON r.id_ticket = s.id_ticket
WHERE r.id_ticket = 5
UNION
SELECT ROUND(SUM(IFNULL(r.total, 0)) + IFNULL(s.total, 0), 2)
FROM refracciones r
  RIGHT OUTER JOIN serviciosrealizados s ON r.id_ticket = s.id_ticket
WHERE s.id_ticket = 5;

You may have to ignore any null rows.

Here's a SQLFiddle as a demo.

You may want to review the database design if possible, as it seems awkward.

Sign up to request clarification or add additional context in comments.

3 Comments

ouch I was testing if is sum just the "servicios" and is not working if I do not insert data in refracciones :(
interface eslumere.elreycalavera.com/img/sql/interface.png

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.