If i give hard coded value inside query it works, but not in case of sub query or column given.
Here is small example of issue i am facing :
Following both query is a type of sub query, like its part of another query, so don't think that where is table 'm' and something else, as it is working already.
So, my query like :
1)
SELECT GROUP_CONCAT(CONCAT(a_u.first_name,' ', a_u.last_name)) AS associated_admin_u
FROM users a_u
WHERE a_u.id IN(m.associated_admin)
GROUP
BY m.id
And m.associated_admin will return a quoted string like '1,10' so this will not work because of its a string.
2)
SELECT GROUP_CONCAT(CONCAT(a_u.first_name,' ', a_u.last_name)) AS associated_admin_u
FROM users a_u
WHERE a_u.id IN(1,10)
GROUP
BY m.id
If i write hard code like 1,10 it works, because it is not a string
So first one is not works because that query is part of another query as a sub query.
And i am sure this question couldn't be duplicate as i am facing it like in this way so any help would be appreciate, thanks reader!
Based on your comments, you need something like:
SELECT GROUP_CONCAT(CONCAT(a_u.first_name,' ', a_u.last_name)) AS associated_admin_u
FROM users a_u
WHERE FIND_IN_SET(a_u.id, TRIM(BOTH '\'' FROM m.associated_admin))
GROUP
BY m.id
This will first trim the quotes from m.associated_admin and then use FIND_IN_SET instead of IN so that you can use a string with comma-separated values.
You can just create a subquery in IN for example:
SELECT group_concat(CONCAT(a_u.first_name,' ', a_u.last_name)) AS associated_admin_u
FROM users a_u WHERE a_u.id IN(
SELECT id FROM mytable WHERE id IN(1,10)
) GROUP BY m.id
Related
I try to make SQL to search some string in database.
In this spesification, The SQL must be dont display one string in database.
my sql like this :
$query = "SELECT * FROM `chatuser` WHERE CONCAT( `fullname`,`image`) LIKE '%".$search_string."%' NOT (`$string is not be displayed`) " ;
is that possible ?
Thanks for help
The correct syntax of LIKE and NOT LIKE as two conditions would be:
SELECT * FROM chatuser
WHERE CONCAT(CustomerName,ContactName) LIKE '%t%'
AND CONCAT(CustomerName,ContactName) NOT LIKE '%m%';
You miss AND Between conditions. Also you have to repeat CONCAT(CustomerName,ContactName).
In the example above we are looking for all CustomerName+ContactName with a t in any place but if it doesn't have an m in any place.
From the docs found at https://www.w3resource.com/mysql/comparision-functions-and-operators/not-like.php
Example: MySQL NOT LIKE operator with (%) percent
The following MySQL statement excludes those rows from the table author, having the 1st character of aut_name ‘W’.
Code:
SELECT aut_name, country
FROM author
WHERE aut_name NOT LIKE 'W%';
And so it seems would work in your situation.
I have a table names and in that table there is a field info data is like this:
ID info
1 'alpha,romeo,ciera,delta'
2 'testing,temp,total'
I am trying to create a select query.
select * from names where info like '%$var%'
$var is data from php.
Problem is i want exact match. If i use above query and in $var if
data is rome then it also return row of romeo.
one more example-
data in table is testing,temp,total
user input data is test then it also return testing
i tried
select * from names where info like '$var%'
and
select * from names where info like '%$var'
but it didn't return data as i expected.
Please advise how can i achieve this.
Note- : This is an example i am not using mysql as its depreciated. I am using mysqli
Append , at begin and end of your target search string.
And then make sure your source string also has those ,
SQL Fiddle Demo
select *
from names
where concat( ',', info , ',') like
concat( '%,', $var, ',%')
The problem is this wont use any index. You should go for FULL TEXT search
Problem is i want exact match. If i use above query and in $var if data is rome then it also return row of romeo.
Don't use the LIKE operator, use exact match operator =
select * from names where info = '$var'
Use , in your query to use it as a delimiter and use multiple conditions to account for the "edge cases".
SELECT *
FROM names
WHERE
info LIKE '%,$var,%' OR
info LIKE '$var,%' OR
info LIKE '%,$var' OR
info = '$var'
If you have rows with info column:
alpha,romeo,ciera,delta
testing,temp,total
rome
foo,test,bar
berlin,paris,madrid,london,rome
venice,milano,rome,firence
black,crome
rome,fome,mome,kome,kome
Query with $var as "rome" will select:
rome
berlin,paris,madrid,london,rome
venice,milano,rome,firence
rome,fome,mome,kome,kome
But not:
alpha,romeo,ciera,delta
black,crome
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.
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
OK so I am retrieving fullname from web page to filter customer list and I am not really sure which part is first name or last name so I need to run a similar query like the one below:
"SELECT sc.*, c.firstname, c.lastname,c.email FROM scoop_customer AS sc LEFT JOIN
customer AS c ON sc.customer_id = c.customer_id WHERE c.firstname + ' ' + c.lastname
LIKE '%".$fullname."%'"
But it doesn't seem working to me even though I tried many times and normally it should have been returning values from DB. Could you please tell me where I am doing wrong?
Try CONCAT
WHERE concat(c.firstname, ' ', c.lastname) LIKE '%".$fullname."%'"
Use CONCAT(c.firstname , ' ' , c.lastname )
CONCAT Would be nice for these operations
Please see the mysql doc
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat
"SELECT sc.*, c.firstname, c.lastname,c.email FROM scoop_customer AS sc LEFT JOIN
customer AS c ON sc.customer_id = c.customer_id WHERE CONCAT(c.firstname, ' ', c.lastname) LIKE '%".mysql_real_escape_string($fullname)."%'"
I'd break full name into first and last and do 2 like checks and get rid of the Wildcard % at the beginning of each. The concatenation and the wildcard starting the like is going to break any indexing you may have on the name fields.
Of course if you only have a couple thousand customers in the table the indexing won't mater much, but when you get into the 100,000's you'll feel it!
Asuming that you haven't escaped it previously I have added mysql_real_escape_string.
For the question, the trick is OR, but not CONCAT
".... WHERE c.firstname LIKE '%".mysql_real_escape_string($fullname)."%'
OR c.lastname LIKE '%".mysql_real_escape_string($fullname)."%'"