简体   繁体   English

Select 来自基于 id 的同一个 MySql 表

[英]Select from within same MySql table based on id

I am building a basic photo album page, which features the selectec photo at the top, and the rest of the album thumbnails below.我正在构建一个基本的相册页面,顶部是 selectec 照片,下面是相册缩略图的 rest。 The structure of the URL is as follows: URL的结构如下:

/photos/photo.php?id=164 /photos/photo.php?id=164

The table structure has fields for event, filename and id表结构包含事件、文件名和 ID 字段

The event field can be attributed to multiple images from the same event.事件字段可以归因于来自同一事件的多个图像。 The event field can also be joined to the event table, which brings together separate races under the same event.事件字段也可以连接到事件表,它将同一事件下的不同种族聚集在一起。

For the tumbnails below, I'd like to select all photos EXCEPT the one where the id is in the URL, for the event which the GET in the URL is associated.对于下面的缩略图,我想 select 除了 ID 在 URL 中的那张照片之外,对于与 ZE6B391A8D2C4D45903DZA23 中的 GET 相关联的事件。

I believe an inner join would be required, but I'm struggling to get it to work.我相信需要一个内部连接,但我正在努力让它发挥作用。 Here is my query, which can select photos which aren't the one being diplayed (from the URL) - but it can't restrict to only showing other photos of the same event as the image being displayed.这是我的查询,它可以 select 照片不是正在显示的照片(来自 URL) - 但它不能限制为仅显示与正在显示的图像相同的事件的其他照片。

SELECT distinct pg.`filename`, pg.`event`, pg.`id` 
    from photogallery pg 
    INNER JOIN photogallery pg2 on pg.`event` = pg2.`event` 
    WHERE pg.`id` <> 302 and pg.`event` = pg2.`event`

Example dataset:示例数据集:

Filename   ¦¦ Event ¦¦ ID
1983-1.jpg ¦¦ 1983  ¦¦ 1
1983-2.jpg ¦¦ 1983  ¦¦ 2
1983-3.jpg ¦¦ 1983  ¦¦ 3
2001-1.jpg ¦¦ 2001  ¦¦ 4
2001-2.jpg ¦¦ 2001  ¦¦ 5
2001-3.jpg ¦¦ 2001  ¦¦ 6

I want the query to only show ID 2 and 3 if the GET is set to 1. But it's showing IDs of 2, 3, 4, 5, 6.如果 GET 设置为 1,我希望查询仅显示 ID 2 和 3。但它显示的 ID 为 2、3、4、5、6。

You can do that with an inner self join on equal event .您可以通过对 equal event进行内部自我加入来做到这一点。 But you need to filter for the sought id in one of the instances and for non equality of the id in both instances.但是您需要在其中一个实例中过滤寻找的id ,并在两个实例中过滤id的不相等性。

SELECT pg1.filename,
       pg1.event,
       pg1.id
       FROM photogallery pg1
            INNER JOIN photogallery pg2
                       ON pg1.event = pg2.event
       WHERE pg2.id = 1
             AND pg1.id <> pg2.id;

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

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