I have a tables like this
Results
-------
id - autoincrement value
TestCase - varchar
Verdict - varchar
AppID - varchar
TestCases
---------
id - autoincrementr value
TestCase - varchar
TestCase_container - varchar
Basically I am displaying the results in php code. while displaying the testcase, I am storing the testcase in a variable. in the while loop of mysql_query, I am creating another connection to DB and passing this variable to TestCases table to get the TestCase_Container assiciated with it.
This is a long way of doing this but I am unable to figure out proper direct SQL query using join or any other thing. Can someone point me in right direction please?
Thanks,
LIke this?
select r.id,r.TestCase,r.Verdict,r.AppId,tc.TestCase_container
from Results r,TestCases tc
where Results.TestCase=TestCases.TestCase
For DB normalization, results table must have testcase_id field instead of TestCase
Kind of hard to say, but I think what you're trying to do is a query like this maybe?
SELECT b.id AS result_id, a.TestCase, b.Verdict, b.AppID, a.id AS testcase_id, a.TestCase_container
FROM TestCases a
LEFT JOIN Results b
ON b.TestCase = a.TestCase;
Would probably be better to be joining on an indexed integer/id field, but that would work fine.
You could easily select all data from your tables by this SQL query:
SELECT Results.TestCase AS TestCase, Results.Verdict AS Verdict, Results.AppID AS AppID, TestCases.TestCase_container AS Container FROM Results JOIN TestCases ON Results.TestCase = TestCases.TestCase
After you should iterate getted array of values in any loop (for example while) like that:
$query = "SELECT Results.TestCase, Results.Verdict, Results.AppID, TestCases.TestCase_container FROM Results JOIN TestCases ON Results.TestCase = TestCases.TestCase";
$res = mysql_query($query) or die(mysql_error());
while ($row=mysql_fetch_array($res)) {
echo $row['TestCase'], ":", $row['Verdict'], ":", $row['AppID'], ":", $row['Container'], "\n";
}
Related
I've the following table:
and an array with following codes: A,C,T in php.
What I need is make a mysqli query (no framework) with the following result:
So I can know the values of ids and field and know that there is no value for C, row 2 doesn't care.
Of course, WHERE IN will filter, and something like:
SELECT * FROM test t1 LEFT JOIN test t2 ON t1.idtest = t2.idtest AND t1.code IN ('A','B','C');
will show B but not C.
I look up for other solutions like an USP and passing a varchar(255) as an array, splitting and etc, but I've aprox 1000 codes so there is no way to do that.
Any help or hint involving MySQL or PHP will be preciated, avoiding of course making a loop of 1000 SELECT for each code that is the thing I'm trying to improve.
Thanks in advance.
I'd recommend sticking to just doing the final processing client side. You're probably dumping the results to a local array or html table anyway, just add code to record which choices had matches and add extra entries for the ones that did not. Otherwise, the alternative is something like this....
SELECT t.*
FROM ( SELECT 'A' AS code
UNION SELECT 'C'
UNION SELECT 'T'
) AS codes
LEFT JOIN test AS t ON codes.code = t.code
...which as you can imagine could get unwieldly with large lists.
Though I am not sure what you were trying to accomplish with the left join to itself.
Possible PHP solution, assuming code is unique in your table.
If you use a single SELECT with IN, like this
SELECT * FROM test WHERE code IN ('A','C','T', 'etc.')
You can index by code as you fetch the results
while ($row = $stmt->fetch()) {
$query_result[$row['code']] = $row;
}
Then iterate the array of codes and fill the result with rows from the query if they exist, or rows with null fields if the query didn't return a row for that code.
foreach ($codes as $code) {
$result = $query_result[$code] ?? ['idtest' => null, 'field' => null, 'code' => $code];
}
I've this code:
public function getAllAccess(){
$this->db->select('accesscode');
$this->db->where(array('chain_code' => '123');
$this->db->order_by('dateandtime', 'desc');
$this->db->limit($this->config->item('access_limit'));
return $this->db->get('accesstable')->result();
}
I need to join it with another table (codenamed table), I've to tell it this. Not really a literal query but what I want to achieve:
SELECT * accesscode, dateandtime FROM access table WHERE chain_code = '123' AND codenames.accselect_lista != 0
So basically accesstable has a column code which is a number, let us say 33, this number is also present in the codenames table; in this last table there is a field accselect_lista.
So I have to select only the accselect_lista != 0 and from there get the corrisponding accesstable rows where codenames are the ones selected in the codenames.
Looking for this?
SELECT *
FROM access_table a INNER JOIN codenames c ON
a.chain_code = c.chain_code
WHERE a.chain_code = '123' AND
c.accselect_lista != 0
It will bring up all columns from both tables for the specified criteria. The table and column names need to be exact, obviously.
Good start! But I think you might be getting a few techniques mixed up here.
Firstly, there are two main ways to run multiple where queries. You can use an associative array (like you've started to do there).
$this->db->where(array('accesstable.chain_code' => '123', 'codenames.accselect_lista !=' => 0));
Note that I've appended the table name to each column. Also notice that you can add alternative operators if you include them in the same block as the column name.
Alternatively you can give each their own line. I prefer this method because I think its a bit easier to read. Both will accomplish the same thing.
$this->db->where('accesstable.chain_code', '123');
$this->db->where('codenames.accselect_lista !=', 0);
Active record will format the query with 'and' etc on its own.
The easiest way to add the join is to use from with join.
$this->db->from('accesstable');
$this->db->join('codenames', 'codenames.accselect_lista = accesstable.code');
When using from, you don't need to include the table name in get, so to run the query you can now just use something like:
$query = $this->db->get();
return $query->result();
Check out Codeigniter's Active Record documentation if you haven't already, it goes into a lot more detail with lots of examples.
I have a simple left join query.
SELECT e.employee_id as employee
, e.badge_id as badge
, e.first_nm as first
, e.last_nm as last
, e.work_phone as work_ph
, e.mobile_phone as mobile_ph
, e.manager_id as man_id
, e.title_id as titl_id
, e.username as user
, e.start_dt as start
, m.employee_id as memp_id
, m.last_nm as m_last
, m.first_nm as m_first
, t.title_nm as titl_nm
FROM employee e
left join employee m
on e.manager_id = m.employee_id
left join title t
on e.title_id = t.title_id
WHERE e.employee_id = 1
If I use column aliases as I have done above, the query works fine. If I do not use aliases, however, some values do not get returned. For example, the following returns a space if I do not give the column an alias.
e.first_nm as first //returns "Robert"
e.first_nm //returns ""
e.first_nm as first_nm //returns "" (alias matches column name)
In this same query,
e.middle_nm //will return "P"
regardless of whether it has an alias or not. I'm baffled.
I have given my tables aliases and I have used the table alias in the column names so there shouldn't be any ambiguous column names.
Any thoughts would be appreciated.
Thanks,
Rob
You have two columns with same name as first_nm and problably the PDO donĀ“t know what return to your code then return simple "". Although they are in diferent tables when came to a record they have the same name... you see the problem?
You have two columns with same name as first_nm and mysql knows how to return them all right, and then return simple "first_nm" for both. And then PDO have to assign them to array members, making field names as array keys. There is only one way, like this
$row['first_nm'] = first col;
$row['first_nm'] = second col;
If you try to see into $row, how many entries you will find?
So, you either have to use FETCH_ROW or give your fields distinct names. It's neither mysql nor PDO to blame - it's just how the things work.
how doHow do we do
select table.value as table_value from table in codeigniter?
The AS part doesnt work because when i try to access the value,
this doesnt work:
$qry_inp = 'select table.value as table_value from table '
$query = $this->db->query($qry_inp);
echo $query->row('table_value ');// this will be empty, but it shouldn`t be
doesn`t matter if its in AR or simple query
Pretty simple thing.
$this->db->select('COLUMN_ACTUAL_NAME as `COLUMN_NAME_YOU_WANT_TO_SHOW`');
i'm joining two tables in which column names are same so i separate both tables columns by using as keyword , this is how you can use AS in codeigniter
$this->db->select("departments.name AS 'dname'");
$this->db->select('positions.name');
Where is that behaviour documented? row doesn't take a column name as a parameter; it optionally takes a row number, and that's it. Access it like any other field:
echo $query->row()->table_value;
I have a situation where lets say i'm trying to get the information about some food. Then I need to display all the information plus all the ingredients in that food.
With my query, i'm getting all the information in an array but only the first ingredient...
myFoodsArr =
[0]
foodDescription = "the description text will be here"
ratingAverage = 0
foodId = 4
ingredient = 1
ingAmount = 2
foodName = "Awesome Food name"
typeOfFood = 6
votes = 0
I would like to get something back like this...
myFoodsArr =
[0]
foodDescription = "the description text will be here"
ratingAverage = 0
foodId = 4
ingArr = {ingredient: 1, ingAmount: 4}, {ingredient: 3, ingAmount: 2}, {ingredient: 5, ingAmount: 1}
foodName = "Awesome Food name"
typeOfFood = 6
votes = 0
This is the query im working with right now. How can I adjust this to return the food ID 4 and then also get ALL the ingredients for that food? All while at the same time doing other things like getting the average rating of that food?
Thanks!
SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood, c.ingredient, c.ingAmount, AVG(b.foodRating) AS ratingAverage, COUNT(b.foodId) as tvotes
FROM `foods` a
LEFT JOIN `foods_ratings` b
ON a.foodId = b.foodId
LEFT JOIN `foods_ing` c
ON a.foodId=c.foodId
WHERE a.foodId=4
EDIT:
Catcall introduced this concept of "sub queries" I never heard of, so I'm trying to make that work to see if i can do this in 1 query easily. But i just keep getting a return false. This is what I was trying with no luck..
//I changed some of the column names to help them be more distinct in this example
SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood, AVG(b.foodRating) AS ratingAverage, COUNT(b.foodId) as tvotes
FROM foods a
LEFT JOIN foods_ratings b ON a.foodId = b.foodId
LEFT JOIN (SELECT fId, ingredientId, ingAmount
FROM foods_ing
WHERE fId = 4
GROUP BY fId) c ON a.foodId = c.fId
WHERE a.foodId = 4";
EDIT 1 more thing related to ROLANDS GROUP_CONCAT/JSON Idea as a solution 4 this
I'm trying to make sure the JSON string im sending back to my Flash project is ready to be properly parsed Invalid JSON parse input. keeps popping up..
so im thinking i need to properly have all the double quotes in the right places.
But in my MySQL query string, im trying to escape the double quotes, but then it makes my mySQL vars not work, for example...
If i do this..
GROUP_CONCAT('{\"ingredient\":', \"c.ingredient\", ',\"ingAmount\":', \"c.ingAmount\", '}')`
I get this...
{"ingredient":c.ingredient,"ingAmount":c.ingAmount},{"ingredient":c.ingredient,"ingAmount":c.ingAmount},{"ingredient":c.ingredient,"ingAmount":c.ingAmount}
How can i use all the double quotes to make the JSON properly formed without breaking the mysql?
This should do the trick:
SELECT food_ingredients.foodId
, food_ingredients.foodName
, food_ingredients.foodDescription
, food_ingredients.typeOfFood
, food_ingredients.ingredients
, AVG(food_ratings.food_rating) food_rating
, COUNT(food_ratings.foodId) number_of_votes
FROM (
SELECT a.foodId
, a.foodName
, a.foodDescription
, a.typeOfFood
, GROUP_CONCAT(
'{ingredient:', c.ingredient,
, ',ingAmount:', c.ingAmount, '}'
) ingredients
FROM foods a
LEFT JOIN foods_ing c
ON a.foodsId = c.foodsId
WHERE a.foodsId=4
GROUP BY a.foodId
) food_ingredients
LEFT JOIN food_ratings
ON food_ingredients.foodId = food_ratings.foodId
GROUP BY food_ingredients.foodId
Note that the type of query you want to do is not trivial in any SQL-based database.
The main problem is that you have one master (food) with two details (ingredients and ratings). Because those details are not related to each other (other than to the master) they form a cartesian product with each other (bound only by their relationship to the master).
The query above solves that by doing it in 2 steps: first, join to the first detail (ingredients) and aggregate the detail (using group_concat to make one single row of all related ingredient rows), then join that result to the second detail (ratings) and aggregate again.
In the example above, the ingredients are returned in a structured string, exactly like it appeared in your example. If you want to access the data inside PHP, you might consider adding a bit more syntax to make it a valid JSON string so you can decode it into an array using the php function json_decode(): http://www.php.net/manual/en/function.json-decode.php
To do that, simply change the line to:
CONCAT(
'['
, GROUP_CONCAT(
'{"ingredient":', c.ingredient
, ',"ingAmount":', c.ingAmount, '}'
)
, ']'
)
(this assumes ingredient and ingAmount are numeric; if they are strings, you should double quote them, and escape any double quotes that appear within the string values)
The concatenation of ingredients with GROUP_CONCAT can lead to problems if you keep a default setting for the group_concat_max_len server variable. A trivial way to mitigate that problem is to set it to the maximum theoretical size of any result:
SET group_concat_max_len = ##max_allowed_packet;
You can either execute this once after you open the connection to mysql, and it will then be in effect for the duration of that session. Alternatively, if you have the super privilege, you can change the value across the board for the entire MySQL instance:
SET GLOBAL group_concat_max_len = ##max_allowed_packet;
You can also add a line to your my.cnf or my.ini to set group_concat_max_lenght to some arbitrary large enough static value. See http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_group_concat_max_len
One obvious solution is to actually perform two queries:
1) get the food
SELECT a.foodId, a.foodName, a.foodDescription, a.typeOfFood
FROM `foods` a
WHERE a.foodsId=4
2) get all of its ingredients
SELECT c.ingredient, c.ingAmount
FROM `foods_ing` c
WHERE c.foodsId=4
This approach has the advantage that you don't duplicate data from the "foods" table into the result. The disadvantage is that you have to perform two queries. Actually you have to perform one extra query for each "food", so if you want to have a listing of foods with all their ingredients, you would have to do a query for each of the food record.
Other solutions usually have many disadvantages, one of them is using GROUP_CONCAT function, but it has a tough limit on the length of the returned string.
When you compare MySQL's aggregate functions and GROUP BY behavior to SQL standards, you have to conclude that they're simply broken. You can do what you want in a single query, but instead of joining directly to the table of ratings, you need to join on a query that returns the results of the aggregate functions. Something along these lines should work.
select a.foodId, a.foodName, a.foodDescription, a.typeOfFood,
c.ingredient, c.ingAmount,
b.numRatings, b.avgRating
from foods a
left join (select foodId, count(foodId) numRatings, avg(foodRating) avgRating
from foods_ratings
group by foodId) b on a.foodId = b.foodId
left join foods_ing c on a.foodId = c.foodId
order by a.foodId