mysql中的复杂查询?

时间:2017-12-05 21:19:49

标签: mysql

 -table : events 
 [id=>1 , data_id =>1 , events_reference =>5 , g_id=>0
  id=>5  , data_id=>1 , events_reference =>NULL , g_id=>1,
  id=>6 . , data_id=>3, events_reference => 5 ,g_id=>0 ]

 - table : data
 [id=> 0 , name=>test1,
  id=>1 , name=>test2,
  id=>3 , name=>tes3 ]

如果g_id_1等于数据表中的data.id(不是data_id列),我想获取包含数据名称的列名g_id_1,并且我还想获​​得基于事件引用显示数据名称的列名g_id_2

另外,我只想提供data.id = 1的数据,例如event.id = 6将不会出现

预期结果:(获取所有活动和+新列调用" g_id_1" +" g_id_2")

{
 "id"=>1,
 events_reference => 5,
 "g_id_1" = > "test 1"
 "g_id_2" => "test 2"
},
{
 "id"=>5,
 events_reference => NULL,
 "g_id_1" = > "test 2" 
 "g_id_2" => NULL
}

我怎么能这样做,我尝试使用sub select但我设法获得第一级但不是第二级,因为events_reference是对同一个表中另一行的引用

select id,events_reference , (SELECT name from data as d where events.events_reference = d.id) as g_id_1, 
(SELECT name from data as d,events as e where e.events_reference = d.id) as g_id_1 

2 个答案:

答案 0 :(得分:0)

我不是一个mySQL wiz,但是很好的是MSSQL,看起来你想要做一个LEFT加入。 那么,如果数据存在,它将返回另一个表。

SELECT events.id, events.events_reference, data.g_id_1, data.g_id_2
FROM events
LEFT JOIN data ON events.events_reference = eventtable.events_reference
LEFT JOIN data data2 ON eventtable.g_id_2 = eventtable2.g_id_1;

很确定这就是你所要求的,如果不是,请告诉我,我会再看看。

CAZ

答案 1 :(得分:0)

加入表格。您需要使用相同表的多个连接来获取嵌套引用。而且你必须使用LEFT JOIN来处理那些没有匹配的情况。

SELECT e1.id, e1.events_reference, d1.name AS g_id_1, d2.name AS g_id_2
FROM events AS e1
LEFT JOIN data AS d1 ON e1.g_id = d1.id
LEFT JOIN events AS e2 ON e1.events_reference = e2.id
LEFT JOIN data AS d2 ON e2.g_id = d2.id

DEMO