简体   繁体   中英

MySQL How to select records with indrect IDs?

My table has a columns labeled primary_key and summary_id . The value in the second field summary_id in each record maps to the primary_key field of another record. There is a third field template_id . I need to select those records for which:

  1. template_id is a certain value. Let's say 4.
  2. primary_key matches at least one of the records' summary_id field.

Please don't tell me to redesign the tables. My next project will have a better design, but I don't have time for that now. I need to do this with one or more queries; the fewer the better. Ideally, there's some way to do this with one query, but I'm okay if it requires more.

在此处输入图片说明

This is how far I've gotten with my own query. (I know it's seriously lacking, which is why I need help.)

SELECT DISTINCT esjp_content.template_id
FROM esjp_content
INNER JOIN esjp_hw_config ON esjp_content.template_id = esjp_hw_config.proc_id
INNER JOIN esjp_assets ON esjp_hw_config.primary_key = esjp_assets.hw_config_id
WHERE
    esjp_content.summary_id > 0
        AND
    (esjp_assets.asset_label='C001498500' OR esjp_assets.asset_label='H0065' OR esjp_assets.asset_label='L0009');

SELECT
    esjp_content.primary_key, esjp_content.template_id, esjp_content.content, esjp_content.summary_id
FROM
    esjp_content
WHERE
    esjp_content.template_id = 4;

I need the records that summary_id points to. For example, if summary_id is 90, then I need the record where primary_key is 90.

在此处输入图片说明

You're looking for the existence of at least one row where summary_id = your primary key. like this.

SELECT *
FROM esjp_content c
WHERE template_id = 4
AND EXISTS (SELECT 1 FROM esjp_content c2 WHERE c2.summary_id = c.primary_key)

You can JOIN same table by using both IDs:

SELECT
    t1.*
FROM
    esjp_content t1
INNER JOIN esjp_content t2 ON t1.summary_id = t2.primary_key
WHERE
    t1.template_id = 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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