SELECT在另一个表中引用少于x次的行

时间:2016-06-21 21:51:39

标签: php mysql

在MySQL中,我有两张桌子,我可以预约"周末":

id bigint(20) unsigned,
label varchar(64),
date_start date,
max_attendees smallint(5) unsigned

和我的与会者:

id bigint(20) unsigned,
name varchar(64),
email varchar(255),
weekend bigint(20) unsigned

我想选择参与者少于max_attendees的所有周末。这包括 0 与会者的周末。

注意:我还需要忽略周末ID" 1" ;

目前,这适用于PHP(我使用Wordpress进行mysql访问),如下所示:

$weekends = $wpdb->get_results("SELECT * FROM $weekends_table
                                   WHERE id <> 1", ARRAY_A);

$open_weekends = array();

foreach ($weekends as $weekend) {
    $id = $weekend['id'];
    $attendees = $wpdb->get_row("SELECT COUNT(id) as attendees
                                    FROM $attendees_table
                                    WHERE weekend = $id", ARRAY_A);

    if ( $attendees['attendees'] < $weekend['max_attendees'] ) {
        $weekend['attendees'] = $attendees['attendees'];
        $open_weekends[] = $weekend;
    }
}

我不能在没有PHP的MySQL中做到这一点吗?我对MySQL的了解并没有延伸到目前为止。你能建议一个查询吗?

2 个答案:

答案 0 :(得分:0)

使用HAVING子句

这是未经测试的,所以你可能不得不玩它,但这里是要点:

SELECT w.*, COUNT(a.name)
FROM weekend w
LEFT JOIN attendees a
  ON w.id = a.weekend
WHERE w.id <> 1
GROUP BY w.id
HAVING (COUNT(a.name) < w.max_attendees) OR (COUNT(a.name) IS NULL)

答案 1 :(得分:0)

一个非常简单的方法是:

SELECT COUNT($attendees_table.id) as attendees
       attendees_table.max_attendees as maximum
FROM weekends_table, attendees_table
WHERE attendees_table.weekend = weekends_table.id
GROUP BY weekends_table.id

您可以使用JOIN ON attendees_table

这也应该是可能的:

SELECT COUNT(attendees_table.id) as attendees
       weekends_table.max_attendees as maximum
FROM weekends_table, attendees_table
WHERE attendees_table.weekend = weekends_table.id
GROUP BY weekends_table.id
HAVING attendees < maximum

这都是未经测试的。我没有你的表或数据,但它可能会让你去?

啊,它没有得到你想要的东西。要包括零参与者,您可以使用子选择:

SELECT  weekends_table.id AS weekend_id
FROM weekends_table
WHERE weekends_table.max_attendees > (SELECT COUNT(*) 
                                      FROM attendees_table 
                                      WHERE attendees_table.weekend = weekends_table.id)

它应该返回周末id,其中至少有一个参加者的空间。再次,完全未经测试,但它可能有效吗?