Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with sql query. Should i be using union?

Tags:

sql

mysql

Have a problem that seems easy on paper but i'm having a big problem figuring out how best to write a single query.

I have a table

CREATE TABLE `profile_values` (  
  `fid` int(10) unsigned NOT NULL default '0',  
  `uid` int(10) unsigned NOT NULL default '0',  
  `value` text,  
  PRIMARY KEY  (`uid`,`fid`),  
  KEY `fid` (`fid`)  
) 

The point of this table is to store profile information on a user.
E.g. a typically row would look like this..

fid | uid | value  
__________________
1   | 77  | Mary  
11  | 77  | Poppins  
1   | 123 | Steve  
11  | 123 | Davis  

Note:

'fid' of '1' represents the first name  
'fid' of '11' represents the last name  
'uid' is a users id within the site.  

What I am trying to achieve is to bring back all uid's that satisfy the condition of first name like 'S%' and last name like 'D%'.
The reason i need this is because i have an autocomplete search box for users on the site.
So if i type 'S' in the search box i will see list of all users that begin with the letter 'S', if i now type a whitespace and 'D' i should now be able to see the list of users who match both conditions.

Does anyone have any idea how this can be accomplished? Thanks in advance.

like image 788
wkmit Avatar asked Jan 22 '26 13:01

wkmit


1 Answers

select firstname.uid, fistname.value, lastname.value
from 
  profile_values firstname
  inner join profile_values lastname 
    on firstname.uid = lastname.uid
WHERE
  firstname.fid = 1
  AND lastname.fid = 11
  AND fistname.value like 'S%'
  AND lastname.value like 'D%'

or, with a users table

select users.uid, fistname.value, lastname.value
from 
  users
  inner join profile_values firstname
    on firstname.uid = users.uid
    AND firstname.fid = 1   
  inner join profile_values lastname 
    on lastname.uid = users.uid
    AND lastname.fid = 11
WHERE
  fistname.value like 'S%'
  AND lastname.value like 'D%'

EDIT:

Forgot to mention: union performs bad on many dbms. If you need a union, there is mostly something wrong with your database model. Use any other alternative before using union.

like image 126
Stefan Steinegger Avatar answered Jan 24 '26 07:01

Stefan Steinegger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!