Simplify some SQL queries.
Permalink
I've never been great with complex sql queries and I this case I think I need some optimizing. With over 300 users this is starting to get out of hand.
Basically I want one query(getAll) where I get all the uID's from UserAttributeValues which have a value of 1 in atBoolean and an avID where akID has the akHandle 'action_enabled'.
I don't know if I'm still making sense haha.
At the moment I using a ton of queries to accomplish this because of that for loop with the if statement.
So I was wondering if someone knew a better and more efficient way to do this.
$db= Loader::db(); $atEnabled = $db->GetOne("select akID from AttributeKeys where akHandle=?",'action_enabled'); $actionEnabled = $db->GetAll("select uID, avID from UserAttributeValues where akID=?",$atEnabled); foreach ($actionEnabled as $saleAr) { if ($db->GetOne("select value from atBoolean where avID=?",$saleAr['avID'])) { } }
Basically I want one query(getAll) where I get all the uID's from UserAttributeValues which have a value of 1 in atBoolean and an avID where akID has the akHandle 'action_enabled'.
I don't know if I'm still making sense haha.
At the moment I using a ton of queries to accomplish this because of that for loop with the if statement.
So I was wondering if someone knew a better and more efficient way to do this.
Thanks for you reply mate.
As you pointed out I just needed to join the 2 tables.
Ended up with this 1 query instead of looping tons of times.
As you pointed out I just needed to join the 2 tables.
Ended up with this 1 query instead of looping tons of times.
$actionEnabled = $db->GetAll("select UserAttributeValues.uID from UserAttributeValues INNER JOIN atBoolean ON UserAttributeValues.avID = atBoolean.avID where UserAttributeValues.akID=? and atBoolean.value=?",array($atEnabled,"1"));
You are testing for 2 conditions in 2 different tables - Maybe traditional SQL would be easier to read ( not concrete ) in this case. I see that in other applications the more complex the SQL that others go back to traditional sql statements.
i.e. I know that this is not like your sql but it is a sample of joining tables ( Jordandev's crud boilerplate )
in the WHERE part on yours
WHERE Attribute.akHandler =? AND atBoolen.avID=? etc.