我有这两张桌子:
table "libs"
|lib_id|name |
|1 |lib01|
|2 |lib02|
|3 |lib03|
|4 |lib04|
|5 |lib05|
table "req_libs"
|lib_id|req_lib_id|
|2 |3 |
|2 |4 |
|4 |3 |
|5 |3 |
|5 |1 |
我应该发出哪些SQL查询才能获得以下结果?
答案 0 :(得分:0)
您可以这种方式使用INNER JOIN:
select t3.*
from libs t1
inner join req_libs t2 on t1.lib_id = t2.lib_id
inner join libs t3 on t2.req_lib_id = t3.lib_id
where t1.name = 'lib01';
答案 1 :(得分:0)
<强> 1。获取lib02所需的所有库的名称。预期 结果:lib03,lib04
SELECT t3.name
FROM libs t1
INNER JOIN req_libs t2 ON t1.lib_id = t2.lib_id
INNER JOIN libs t3 ON t2.req_lib_id = t3.lib_id
WHERE t1.name = 'lib02';
<强> 2。获取使用lib03的所有库的名称。预期结果: lib02,lib04,lib05 强>
SELECT libs.name
FROM libs
WHERE libs.lib_id IN (
SELECT req_libs.lib_id
FROM libs, req_libs
WHERE libs.name = 'lib03'
AND libs.lib_id = req_libs.req_lib_id
);
SqlFiddle:http://sqlfiddle.com/#!9/2731df/18