Как получить все данные из таблицы, которую вы также запрашиваете для AVG

0

Здравствуйте, мне нужна помощь в решении проблемы ниже. Спасибо заранее.

У меня три таблицы

attachments sun_individual sun_reviews

Я хочу выбрать names, profession and reviewed пользователей names, profession and reviewed sun_individual его/ее ID от sun_individual и join к его profile photo из attachments таблицу, затем получить его/ее reviews (each review and rate) и average RATE

TABLE: sun_individual

id|sun_id|first_name|last_name |sun_profession|sun_verified_date|sun_verified|flg
---------------------------------------------------------------------------------
20|SV-001|Alex      | James    | Doctor       |2017-12-08       | 1         |1           
21|SV-002|Jane      | Rose     | Programmer   |2017-12-08       | 1         |1

TABLE: sun_reviews

id|user_id|rev_txt   |rev_rate|rev_date  |flg                                    
----------------------------------------------------                                
1 |20     | the best | 4      |2017-12-09|1
2 |21     | know CLI | 2      |2017-12-09|1
3 |20     | recommend| 3      |2017-12-09|0
4 |20     | so far   | 3      |2017-12-09|1

TABLE: attachments

id|user|type    |path              |flg
----------------------------------------
88|20  |passport|/upload/img128.jpg|1
89|21  |passport|/upload/img008.jpg|1

flg:1 означает, что значение активно, flg:0 значение игнорируется

My Code is :

SELECT 
      sun_reviews.rev_txt As txtReview, sun_reviews.rev_date As dateReview,
      sun_reviews.rev_rate As rateReview,

      AVG(sun_reviews.rev_rate) As avgREV,
      concat(sun_individual.first_name, sun_individual.last_name) As name,

      sun_individual.sun_profession As profession, 
      sun_individual.sun_verified_date As dateVerified,

      CASE when sun_verified = 1 then 'VERIFIED' else 'EXPIRED' END As status,

      attachments.path As photo 
FROM 'sun_individual'

     LEFT JOIN sun_reviews ON sun_reviews.user_id = sun_individual.id
     INNER JOIN attachments ON attachments.user = sun_individual.id

WHERE attachments.type = 'passport' AND attachments.flg = 1 
      AND sun_reviews.flg = 1 AND sun_individual.flg = 1 
      AND sun_individual.sun_id LIKE '%SV-001'

Я хочу архивировать, когда кто-то ищет пользователя (скажем, SV-001), когда код вводится для получения результата, например

result for: SV-001

txtReview|dateReview|rateReview|avgREV|name      |profession | dateVerified | photo
------------------------------------------------------------------------- -----------------
the best |2017-12-09|4         |3.5000|Alex James| Doctor    | 2017-12-08   |/upload/img128.jpg  
so far   |2017-12-09|3         |3.5000|Alex James| Doctor    | 2017-12-08   |/upload/img128.jpg

Я хочу получить результат, как выше, однако, когда я запускал запрос, я получаю только один обзор

txtReview|dateReview|rateReview|avgREV|name      |profession | dateVerified | photo
------------------------------------------------------------------------- -----------------
the best |2017-12-09|4         |3.5000|Alex James| Doctor    | 2017-12-08   |/upload/img128.jpg  

Я думаю, что что-то делает неправильно... Если вы знаете, что решение моей проблемы любезно мне помогло.

Благодарю.

Теги:

1 ответ

1
Лучший ответ
select
  a.rev_txt                    as txtReview,
  a.rev_date                   as dateReview,
  a.rev_rate                   as rateReview,
  d.avgRev                     as avgRev,
  b.first_name || b.last_name  as name,
  b.sun_profession             as profession, 
  b.sun_verified_date          as dateVerified,
  case
    when sun_verified = 1 then 'VERIFIED' 
    else 'EXPIRED' 
  end                          as status,
  c.path                       as photo
from
  sun_reviews a
  join
  sun_individual b
  on a.user_id = b.id
  join
  attachments c
  on c.user_id = b.id
  join
  (
    select 
      user_id,
      avg(rev_rate) as avgRev
    from
      sun_reviews
    where
      flg = 1
    group by 
      user_id
  ) d
  on d.user_id = b.id
where
  c.type = 'passport' and
  c.flg = 1 and
  a.flg = 1 and 
  b.flg = 1 and
  b.sun_id LIKE '%SV-001';

 txtreview | datereview | ratereview |       avgrev       |   name    | profession | dateverified |  status  |       photo        
-----------+------------+------------+--------------------+-----------+------------+--------------+----------+--------------------
 the best  | 2017-12-09 |          4 | 3.5000000000000000 | AlexJames | Doctor     | 2017-12-08   | VERIFIED | /upload/img128.jpg
 so far    | 2017-12-09 |          3 | 3.5000000000000000 | AlexJames | Doctor     | 2017-12-08   | VERIFIED | /upload/img128.jpg
(2 rows)

Когда у вас есть группа, все столбцы в наборе результатов должны быть либо по столбцам, либо по агрегатам. Я предполагаю, что вы используете MySQL, который не обеспечивает этого. Вы должны применять его сами, хотя в противном случае он становится очень запутанным.

  • 0
    Запрос работал отлично, спасибо. Я также посмотрю на то, что " Вы должны принудительно применить это все же ". Благодарю вас

Ещё вопросы

Сообщество Overcoder
Наверх
Меню