MySQL查询正在复制名称字段

时间:2019-07-10 14:41:28

标签: mysql sql

我正在尝试创建一个SQL查询,该查询返回每个与会者的会话检入总数。但是,当我运行以下查询时,它将在所有内容上重复全名。

尝试使用不同的查询查询,但仍获得相同的结果

SELECT
CONCAT(ea.first_name, ' ', ea.last_name) as full_name,
es.name AS name,
es.event_id AS event_id,
(   SELECT COUNT(DISTINCT esc.event_attendee_id)
    FROM event_session_checkin esc
    WHERE(esc.event_session_id =es.id) 
) AS attendee_count
FROM event_session es, event_attendee ea;

结果:

+----------+-----------+-----------+--------------+
|full_name |event_name |event_id   |attendee_count|
+-------------------------------------------------+
|anita_roy |name_exam  |event_exam1|      2       |
|anita_roy |name_exam  |event_exam2|      3       |
|anita_roy |name_exam  |event_exam3|      5       |
|anita_roy |name_exam  |event_exam4|      6       |
|anita_roy |name_exam  |event_exam5|      7       |

2 个答案:

答案 0 :(得分:-1)

尝试

SELECT CONCAT(ea.first_name, ' ', ea.last_name) as full_name,es.name AS name,
enter code here es.event_id AS event_id,
(SELECT COUNT(DISTINCT esc.event_attendee_id)
        FROM event_session_checkin esc
        WHERE(esc.event_session_id =es.id) ) AS attendee_count
FROM
event_session es, event_attendee ea group by full_name;

答案 1 :(得分:-1)

当然,因为您没有指定表的关联方式!

SELECT * FROM person,address

上面的查询将仅返回每个人和每个地址。它忽略表之间的任何关系,如果有200个人和100个地址,则每个地址的每个人都会得出20,000个结果。每个人名将重复100次,每个地址一次。每个地址将重复200次,每个人一次。即使您在表之间声明了外键,也没关系; mysql不会使用它们来推断表之间的关系。 必须明确告知数据库该人的哪一列与地址的哪一列相关:

SELECT * FROM person p INNER JOIN address a on p.home_address_id = a.id

表可以多次连接:

SELECT * FROM  
  person p 
  INNER JOIN address ha on p.home_address_id = ha.id
  INNER JOIN address wa on p.work_address_id = wa.id

请阅读,吸收,理解和重写查询,以便您明确声明event_session中的哪一列与event_attendee中的哪一列相关