![](/img/trans.png)
[英]MySQL: Using JOINS with WHERE clause to get all records from one table and available records from the other
[英]How to get all records from one table and null with other table
嗨,我有两个表event_service和约会约会,其中我在event_service表中有两个记录,在booking_feedback中有一个记录,因此我想将记录与event_service表匹配,将空记录与约会_feedback匹配。
请遵循我的表格结构
第一个表: event_service
....................................
evsr_id evsr_ev_id staff_id
....................................
1 101 1
2 101 2
第二张表: appoitment_feedback
....................................
fd_id fd_app_id fd_comment
....................................
1 101 test
我想要这个输出:
.................................................
evsr_id evsr_ev_id staff_id fd_comment
.................................................
1 101 1 test
2 101 2 null
我已经在下面的查询中尝试过,但是它没有给出空值,而是给出了注释的重复值,即test,但是在ational_feedback表中只有一个条目,因此我想从event_service表中获得两个记录,从约会和反馈表中获得一个记录,并与该记录相对应。
SELECT appointment_feedback.`fd_id`,`fd_app_id`,`fd_comment`,`fd_service_rat`
FROM event_service
left join `appointment_feedback`
on event_service.evsr_ev_id=appointment_feedback.fd_app_id
WHERE appointment_feedback.fd_app_id='3959'
该查询给出了错误的输出:-
..............................................
fd_id fd_app_id fd_comment fd_service_rat
.............................................
1 101 test 0
1 101 test 0
我已经使用了简单的LEFT JOIN来提供请求的输出。
DECLARE @event_service AS Table
(
evsr_id INT,
evsr_ev_id INT,
staff_id INT
)
DECLARE @appoitment_feedback AS Table
(
fd_id INT,
fd_app_id INT,
fd_comment VARCHAR(50)
)
INSERT INTO @event_service VALUES(1,101,1)
INSERT INTO @event_service VALUES(2,101,2)
INSERT INTO @appoitment_feedback VALUES(1,101,'test')
SELECT
es.*,
af.fd_comment
FROM @event_service es
LEFT JOIN @appoitment_feedback af ON es.evsr_ev_id=af.fd_app_id
AND es.evsr_id=af.fd_id
输出:
根据您的问题,您拥有正确的工具,但未正确使用它们。
这是您当前的查询:
SELECT appointment_feedback.`fd_id`,`fd_app_id`,`fd_comment`,`fd_service_rat` FROM `appointment_feedback` left join event_service on event_service.evsr_ev_id=appointment_feedback.fd_app_id WHERE appointment_feedback.fd_app_id='3959'
您所需要做的就是交换表,以便从event_service
选择,并保留join appointment_feedback
event_service
,因此这应该是您的新查询:
SELECT appointment_feedback.`fd_id`,`fd_app_id`,`fd_comment`,`fd_service_rat`
FROM event_service
left join `appointment_feedback`
on event_service.evsr_ev_id=appointment_feedback.fd_app_id
WHERE appointment_feedback.fd_app_id='3959'
LEFT JOIN从第一个(最左侧)表开始,然后是任何匹配的第二个(最右侧)表记录开始执行联接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.