我在MySQL数据库中有两个表,如下所示:
service_id |userid | service_name | pending | accepted|completed
-----------+------------+--------------+----------+---------+--------
1 | 1 | Spa | 1 |0 |0
2 | 2 | Cleaning | 0 |1 |0
3 | 3 | General | 1 |0 |0
id | service_id | Userid | status | accepted_date
----+---------------+--------+--------------+---------------
1 | 1 | 1 | Pending | 2018/03/02
2 | 2 | 2 | Pending | 2018/03/02
3 | 2 | 2 | Accepted | 2018/03/05
4 | 3 | 3 | Pending | 2018/03/06
service_id | service_name | userid| Status | Date
-----------+----------------+-------+------------+------------+---------
1 | Spa | 1 | Pending | 2018/03/02
2 | Cleaning | 2 | Accepted | 2018/03/05
3 | General | 3 | Pending | 2018/03/06
对于每个服务用户opt,状态将在另一个表请求状态中更新。
我希望输出加入2个表,每个服务的状态。例如。对于服务ID 2,它已被接受,因此它在第二个表中有2个条目。 我尝试使用join,但是它取出了挂起并接受了服务2,它应该只获取一个。
SELECT a.*, b.* FROM service a left outer join request_statusb on a.service_id =b.service_id
怎么做。?任何帮助请
答案 0 :(得分:1)
试试这个
SELECT a.*, b.*
FROM service a
INNER JOIN request_status b ON a.service_id = b.service_id
WHERE b.id = (SELECT max(id) FROM request_status rs WHERE rs.service_id = a.service_id)