Joshua Wieczorek
Joshua Wieczorek

Reputation: 735

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!

enter image description here

Upvotes: 2

Views: 3524

Answers (2)

Steven Moseley
Steven Moseley

Reputation: 16325

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'

Upvotes: 1

Thorsten Kettner
Thorsten Kettner

Reputation: 94914

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');

Upvotes: 0

Related Questions