Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SELECT ALL ROWS WHERE ALL CRITERIA IS MET EVEN ACROSS MULTIPLE RECORDS

Status
Not open for further replies.

aviddv1

Programmer
Sep 30, 2005
2
US
Hey there,

I'll try to make this easy to understand cause apparently I'm a moron. I have a table that has two columns. Column 1 is UID and column 2 is Attribute. Lets say I have 10 records for 5 different UIDs. Some of the users have more than one record meaning they have more than one attribute. (so far, so good)

I want to write a query that will show me only the users who are both tall and have blonde hair for instance. Eventually I'll need to match more than 2 attributes, but ill take what i can get for now.

I know how to query people who are tall or people who have blonde hair. I've been using:

... WHERE Attribute IN ("tall","blonde")

Any ideas?

Thanks for your time,
Ward
 
SELECT UID, ATTRIBUTE
FROM TABLE
WHERE (ATTRIBUTE = 'TALL' AND ATTRIBUTE = 'BLONDE')

Just add more attributes as you need them, i.e.;

WHERE (ATTRIBUTE = 'TALL' AND ATTRIBUTE = 'BLONDE' AND ATTRIBUTE = 'BLUE EYES')
 
I tried that but it doesn't seem to work on my end.

thanks,
Ward
 
If you're using MySQL 4.1 or later, you could try:
[tt]
SELECT uid
FROM
(
SELECT
uid,
CONCAT(',',GROUP_CONCAT(attribute),',') a
FROM tbl1
GROUP BY uid
)
q
WHERE
a LIKE '%,tall,%' AND attrs LIKE '%,blonde,%'
[/tt]
 
Or, slightly simpler:
[tt]
SELECT uid
FROM
(
SELECT uid, GROUP_CONCAT(attribute) a
FROM tbl1
GROUP BY uid
)
q
WHERE
FIND_IN_SET('tall',a)
AND FIND_IN_SET('blonde',a)
[/tt]
 
Code:
select UID
  from daTable
 where Attribute in ('tall','blonde') 
group
    by UID
having count(*) = 2
easily extensible to 3 or more attributes

Code:
select UID
  from daTable
 where Attribute in ('tall','blonde',gorgeous') 
group
    by UID
having count(*) = 3

r937.com | rudy.ca
 
Rudy's solution should work too, as long as you have no duplicate records. For example, if a particular UID has two 'tall' records but no 'blonde' record, that UID will be included in the result set.
 
you're right, tony, but ...

1. that shouldn't happen, because {UID,Attribute} should be the primary key

2. even if it does happen, just change

... having count(*) = n

to

having count(distinct Attribute) = n


r937.com | rudy.ca
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top