多个查询,还是嵌套?

时间:2016-07-01 12:23:50

标签: mysql

我有两个频道。

第一个频道是'预订'。这包含member_idtour_id

第二个频道是'游览'。这包含上述tour_id引用的游览详细信息。

我需要在“游览”频道中查询字段,为满足查询的用户获取tour_id。然后,我需要找到tour_id匹配的所有“预订”条目,其中一个是查询属实。

完成两个SQL查询或嵌套查询是否更好?如果嵌套,怎么办?

exp_channel_data | CHANNEL_ID | entry_id | field_id_1 | ... |

exp_channel_titles | CHANNEL_ID | entry_id | AUTHOR_ID | ... |

SELECT titles.author_id
FROM exp_channel_data AS tours
LEFT JOIN exp_channel_titles AS titles ON bookings.entry_id = titles.entry_id
LEFT JOIN exp_channel_data AS bookings
    ON tours.entry_id = bookings.entry_id
    AND bookings.channel_id = '17'
WHERE tours.channel_id = '5'
AND tours.field_id_34 = 'DSV04'
$sql_1 = "
    SELECT entry_id
    FROM exp_channel_data 
    WHERE field_id_34 LIKE 'adas%'
";

$query_1 = ee()->db->query($sql_1);
$test = $query_1->result_array();

$uids = Array();
foreach($test as $u) $uids[] = $u['entry_id'];
$list = implode(",",$uids);


$sql_2 = "
    SELECT ct.author_id
    FROM exp_channel_data AS cd
    LEFT JOIN exp_channel_titles AS ct ON cd.entry_id = ct.entry_id 
    WHERE field_id_227 IN ($list)
";

$query_2 = ee()->db->query($sql_2);
$test_2 = $query_2->result_array();

1 个答案:

答案 0 :(得分:2)

假设这样的表结构:

|channel_id|tour_id|member_id|field1|...|
-----------------------------------------
|tours     |1      |NULL     |abc   |   |
|tours     |2      |NULL     |def   |   |
|booking   |1      |1        |      |   |
|booking   |1      |2        |      |   |
|booking   |2      |3        |      |   |

您可以自己加入表格以获得您正在寻找的结果......

SELECT
    booking.tour_id
    booking.member_id
FROM
    my_table tours
    LEFT JOIN my_table booking
        ON tours.tour_id = booking.tour_id
        AND booking.channel_id = 'booking'
WHERE
    tours.channel_id = 'tours'
    AND tours.field1 = 'abc'

编辑作为更新问题的后续行动

我理解:

  • 您希望查找所有预订的所有预订作者 ,其中field_id_34以“adas”开头。
  • 预订的
  • 作者保留在表exp_channel_titles
  • 预订之旅保留在表格exp_channel_data中,列channel_id用于区分预订(17)和巡演(5)。
  • 预订游览通过游览entry_idfield_id_227进行关联>预订
  • 预订作者通过预订entry_identry_id exp_channel_titles
  • 链接

因此,这应该在一个查询中为您提供作者列表:

SELECT
    titles.author_id
FROM
    exp_channel_data tours
    LEFT JOIN exp_channel_data bookings
        ON bookings.channel_id = 17
        AND bookings.field_id_227 = tours.entry_id
    LEFT JOIN exp_channel_titles titles
        ON titles.entry_id = bookings.entry_id
WHERE
    tours.channel_id = 5
    AND tours.field_id_34 LIKE 'adas%'