简体   繁体   English

MYSQL联接-唯一ID位于1个表中

[英]MYSQL Joins - Where Unique ID lies in 1 table

I have 2 tables I want to connect in a strange / dangerous / non-dynamic way. 我有2个表格,我想以一种奇怪/危险/非动态的方式进行连接。 I don't have control over these tables. 我无法控制这些表。 I'm trying to pull the summary from one table that contains event id but not category id but I need to reference another table to make sure that said event is in said category. 我正在尝试从一个包含事件ID包含类别ID的表中提取摘要,但是我需要引用另一张表以确保所述事件在所述类别中。 This table contains both event id and cat id . 该表包含事件ID猫ID I'm trying to join them but I keep getting returned nothing. 我正在尝试加入他们,但我一无所获。

I know this is dangerous, but I also have control over the categories so I know that my category ID's will not change unless I specify. 我知道这很危险,但是我也可以控制类别,因此我知道除非指定,否则类别ID不会更改。 Since it auto-increments - my categories will be 1, 2, 3. 由于它会自动增加-我的类别将是1、2、3。

The Gist of my Tables 我的餐桌要点

*events_vevent*

 - ev_id 
 - catid

 ---

*events_vevdetail*

 - evdet_id
 - summary

My Code 我的密码

$data = array();
for($i = 0; $i < 3; $i++){
    $summary = array();
    $query_summary = mysql_query("SELECT events_vevdetail.summary FROM 
                     events_vevdetail, events_vevent 
                     WHERE 'events_vevent.evdet_id = $i' LIMIT 5") 
    or die(mysql_error());

    while(($row = mysql_fetch_array($query_summary)))
        $summary[] = $row[0];

    switch($i){
        case 0:
            $data['cat1'] = $summary;
            break;
        case 1:
            $data['cat2'] = $summary;
            break;
        case 2:
            $data['cat3'] = $summary;
            break;
    }
}

echo json_encode($data);

Explanation 说明

so what I'm trying to do is: Since I know category 1 will always have an ID of 0, I want to pull the most recent 5 posts, but only posts in category ID 0. Same for cateogry2 and 3. Right now I'm getting empty arrays. 所以我想要做的是:因为我知道第1类总是会有0的ID,我想拉最近的5个员额,但在产品ID唯一的帖子现在 0同为cateogry2和3. 我正在获取空数组。 I feel like I need 2 mysql queries (one for each table) and then compare but I'm not 100% sure and would rather do this the right way than the long way. 我觉得我需要2个mysql查询(每个表一个),然后进行比较,但我不是100%肯定,宁愿以正确的方式而不是长期的方式进行此操作。

tl;dr is my MYSQL right? tl; dr是我的MYSQL对吗?

This query will return top most 5 records from each category. 该查询将返回每个类别的前5条记录。

SELECT e1 . *
FROM events_vevent e1
LEFT OUTER JOIN events_vevent e2 ON 
( e1.catid = e2.catid AND e1.ev_id < e2.ev_id )
GROUP BY e1.ev_id
HAVING COUNT( * ) < 5
ORDER BY catid, ev_id DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM