E
E
eldar_web2018-06-28 13:12:11
SQL
eldar_web, 2018-06-28 13:12:11

How to write a SQL query with a specific condition?

There are two tables prices and price_items (belongs to prices - references price_id).
For these two tables, there is one table - ratings ratings with fields:
type_id : here can be id prices or price_items type_name
: 'price' or 'price_items'
ball : respectively rating
if it does not have a record, then we take ball from the parent price?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2018-07-04
@eldar_web

The purpose of the query is not entirely clear, why it simply displays a column of values ​​​​without keys.
A little cumbersome, but you can try this:

select prt.ball 
   from price_ratings prt
 where prt.type_name = 'price_items'
  union
  select prt.ball 
    from price_ratings prt
       left join price_items pr
                on pr.price_id       = prt.type_id
       left join price_ratings pp
                on pp.type_id       = pr.id
              and pp.type_name = 'price_items'  
   where prt.type_name  = 'price'
       and pp.ball     is null

or so
select isnull(prt.ball, pri.ball)
  from price_items pi
  left join price_ratings prt
         on prt.type_id   = pi.id
    and prt.type_name = 'price_items' 
  left join price_ratings pri
         on pri.type_id   = pi.price_id
    and pri.type_name = 'price'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question