简体   繁体   中英

Join subquery with a count function

I have four tables:

  1. Room (holds room details)

  2. property ( holds property details)

  3. property interest (linking table matching customers with properties interested in)
  4. buying_potential_customer (customer details).

I currently have this query which tells me how many rooms in each property has.

SELECT
  property.property_id,
  property.property_address_first_line,
  COUNT(room.property_id) AS number_of_rooms
FROM room
INNER JOIN property
  ON room.property_id = property.property_id
GROUP BY property.property_id,
         property.property_address_first_line
ORDER BY property.property_id;

The property_interest and buying_potential interest need to be joined to this also.

This is the property interest table

财产利息表

This is the buying potential customer table

购买潜在客户

In the end I need, the data from property interest which matches property with buyer but with the buyer's first and last name attached, additionally counting the number of rooms in the property which is the query above. It seems I would need a subquery but am not sure how to complete this, and help would be appreciated

Sorry I am quite new to SQL.

If I understand your aim :)

You must write a query as main table your middle table property_interest , so you can join it with others parent tables, as follow:

SELECT bpc.buying_customer_first_name || bpc.buying_customer_surname,
(SELECT COUNT(*)
FROM room r
JOIN property p
    ON r.property_id = p.property_id
WHERE p.property_id = pi.property_id)
FROM property_interest pi
JOIN buying_potential_custoter bpc
    ON pi.buying_customer_id = bpc.buying_customer_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM