我正试图在mysql中检索匹配和不匹配的记录。
center_wise_test_rates:
lab_id category_name test_id test_name rate
------ ------------- -------- --------- ------
2 Cardiology 9 Blood Sug 1200
2 Cardiology 10 Total Cholesterol 1500
2 Cardiology 11 HDL 1100
2 Cardiology 12 LDL 750
test_list
test_id category_name test_name
------- ------------- ---------
9 Cardiology Blood Sug
10 Cardiology Total Cholesterol
11 Cardiology HDL
12 Cardiology LDL
57 Cardiology abc
从基于category_name和lab_id的center_wise_test_rates和test_list表中,将获得匹配记录,但不匹配的记录,即测试名称'abc'未获得。
我的查询:
SELECT cwtr.lab_id
,cwtr.category_name
,cwtr.test_id
,cwtr.test_name
,cwtr.rate
FROM `center_wise_test_rates` AS cwtr
LEFT OUTER JOIN test_list AS tl ON tl.category_name = (SELECT DISTINCT category_name
FROM center_wise_test_rates
WHERE category_name='Cardiology')
AND tl.test_id = cwtr.test_id
WHERE cwtr.lab_id = '2'
AND cwtr.category_name = 'Cardiology'
输出:
lab_id category_name test_id test_name rate
------ ------------ -------- --------- ----
2 Cardiology 9 Blood Sug 1200
2 Cardiology 10 Total Cholesterol 1500
2 Cardiology 11 HDL 1100
2 Cardiology 12 LDL 750
预期输出:
lab_id category_name test_id test_name rate
------ ------------- -------- --------- ----
2 Cardiology 9 Blood Sug 1200
2 Cardiology 10 Total Cholesterol 1500
2 Cardiology 11 HDL 1100
2 Cardiology 12 LDL 750
2 Cardiology 57 abc Null
谢谢。
答案 0 :(得分:0)
您所需要的只是左加入-
SELECT (SELECT lab_id
FROM center_wise_test_rates
WHERE category_name = tl.category_name
LIMIT 1) lab_id
,tl.category_name
,tl.test_id
,tl.test_name
,cwtr.rate
FROM test_list tl
LEFT JOIN center_wise_test_rates cwtr ON tl.test_id = cwtr.test_id
AND tl.category_name = cwtr.category_name
Here是演示。
答案 1 :(得分:0)
它将从TABLE1中选择条件是否匹配的所有值。
SELECT coulmn1, column2 FROM TABLE1 LEFT JOIN TABLE2 ON TABLE1.ID= TABLE2.ID WHERE NAME = 'ABC'