Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Another (stupid) SQL question!

Options
  • 10-11-2008 12:25pm
    #1
    Registered Users Posts: 383 ✭✭


    Hey guys,

    What I am trying to do is a search on users "profile". So if one of the values matches, that all rows with the same "user_id" are returned.

    I know it can be done in two straight queries, first search for value, then search on returned user_id, but can it be done in 1 search? Bonus question would be which way would be faster, 1 'complex' query or two shorter ones?

    Thanks in advance! :)
    CREATE TABLE IF NOT EXISTS `fieldvalues` (
      `id` int(11) NOT NULL auto_increment,
      `fieldname_id` int(11) NOT NULL,
      `user_id` int(11) NOT NULL,
      `value` varchar(255) collate latin1_general_ci NOT NULL,
      PRIMARY KEY  (`id`)
    )
    

    Query 1
    SELECT `Fieldvalue`.`id`, `Fieldvalue`.`fieldname_id`, `Fieldvalue`.`user_id`, `Fieldvalue`.`value` FROM `fieldvalues` AS `Fieldvalue` WHERE `Fieldvalue`.`value` LIKE "%Some text%"

    Query 2
    SELECT `Fieldvalue`.`id`, `Fieldvalue`.`fieldname_id`, `Fieldvalue`.`user_id`, `Fieldvalue`.`value` FROM `fieldvalues` AS `Fieldvalue` WHERE `Fieldvalue`.`user_id` = user_id from query 1


Comments

  • Registered Users Posts: 2,494 ✭✭✭kayos


    SELECT 
    	FV.id, 
    	FV.fieldname_id, 
    	FV.[user_id], 
    	FV.[value] 
    FROM 
    	fieldvalues AS FV 
    	JOIN (SELECT 
    			[user_id]
    		  FROM 
    			fieldvalues
    		 WHERE 
    			[value] LIKE "%Some text%"
    		) AS D ON FV.[user_id] = d.[user_id]
    
    


  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    At first I thought that the first query will return all of the data that you need, but I see what you're doing.

    The easiest way to do this is using subqueries, assuming that you're using mysql:
    SELECT 
    	`Fieldvalue`.`id`, 
    	`Fieldvalue`.`fieldname_id`, 
    	`Fieldvalue`.`user_id`, 
    	`Fieldvalue`.`value` 
    FROM 
    	`fieldvalues` AS `Fieldvalue` 
    WHERE 
    	`Fieldvalue`.`user_id` IN (
    				SELECT 
    					`Fieldvalue`.`user_id` 
    				FROM 
    					`fieldvalues` AS `Fieldvalue` 
    				WHERE 
    					`Fieldvalue`.`value` LIKE "%Some text%"
    			)
    


  • Registered Users Posts: 383 ✭✭cherrio


    Works perfect, thx guys.


Advertisement