简体   繁体   中英

SQL Select Where Join Table

Is there a way to do a select to do something like the following without running two queries? The first query gets the "id" of the a column and the second queries another table returning where that "id" matches?

SELECT `name` 
FROM `attributes` 
INNER JOIN `attribute_vals` 
ON `attributes`.`id`=`attribute_vals`.`attr_id`
WHERE `name`='weight' 

Thank you for your answers!

Just a quick graphical representation of what I am trying to achieve!

在此处输入图片说明

Making a few assumptions about your DB design:

  1. the name column is in the attributes table,
  2. the attr_id, name combination is unique, and
  3. there's a val column in the attribute_vals table.

It sounds like you want a simple join limiting the values table by the name in the attributes table.

You can then get associated attribute_vals data in a single query.

SELECT
    `av`.`id`,
    `av`.`attribute_id`,
    `av`.`value`
FROM `attributes` AS `a`
INNER JOIN `attribute_vals` AS `av`
    ON `a`.`id`=`av`.`attr_id`
WHERE `a`.`name`= 'weight'

This query gets you all attribute values for the attribute 'weight'. Is this what you want?

select *
from attribute_vals
where attribute_id in (select id from attributes where name= 'weight');

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