select from one table, count from another where id's linked

后端 未结 2 348
青春惊慌失措
青春惊慌失措 2020-12-08 22:14

heres my code:

$sql = mysql_query(\"select c.name, c.address, c.postcode, c.dob, c.mobile, c.email, 
                    count(select * from bookings where b         


        
相关标签:
2条回答
  • 2020-12-08 22:28

    Your query incorrectly uses COUNT, which has been covered by @Will A's answer.

    I would also like to suggest a possibly better constructed alternative, which, I think, reflects the same logic:

    SELECT
      c.name,
      c.address,
      c.postcode,
      c.dob,
      c.mobile,
      c.email,
      COUNT(*) AS purchased,
      COUNT(b.the_date > $now OR NULL) AS remaining
    FROM customers AS c
      INNER JOIN bookings AS b ON b.id_customer = c.id
    GROUP BY c.id
    ORDER BY c.name ASC
    

    Note: Normally you are expected to include all the non-aggregated SELECT expressions into GROUP BY. However MySQL supports shortened GROUP BY lists, so it's enough to specify the key expressions that uniquely identify all the non-aggregated data you are pulling. Please avoid using the feature arbitrarily. If a column not included in GROUP BY has more than one value per group, you have no control over which value will actually be returned when pulling that column without aggregation.

    0 讨论(0)
  • 2020-12-08 22:40

    Try changing the likes of...

    count(select * from bookings where b.id_customer = c.id)
    

    ...to...

    (select count(*) from bookings where b.id_customer = c.id)
    
    0 讨论(0)
提交回复
热议问题