I need to concat column name depending on row value. Below is my table format:-
Table Name = tbl_occupancy
so from this table, I need to concat below column if their value is 1:-
working_people
owner_occupied
students
dss_referrals
local_authority
output would be in below format:-
Working People/Owner Occupied/Students/Dss Referrals/Local Authority
when all of these columns value are one.
Suppose if working_people & dss_referrals = 1 then my output will be below:-
Working People/Dss Referrals
trying for one day. not found any solution till now.
I need this output in a single row mentioned above. Because this query will work as an sub query in my report module. And this output will be shown as a column in xls sheet.
Any help plz.
You can use CASE inside the CONCAT() function
SELECT
DISTINCT risk_reference,
CONCAT(
CASE WHEN `working_people` = 1 THEN 'Working People /' ELSE '' END ,
CASE WHEN `owner_occupied` = 1 THEN 'Owner Occupied /' ELSE '' END ,
CASE WHEN `students` = 1 THEN 'Students /' ELSE '' END ,
CASE WHEN `dss_referrals` = 1 THEN 'Dss Referrals/' ELSE '' END ,
CASE WHEN `local_authority` = 1 THEN 'Local Authority' ELSE '' END
) `concat_columns`
FROM
`table`
EDIT:
You can use DISTINCT to get the distinct results but in your table you have multiple rows so there will be multiple results although you can use a GROUP BY risk_reference but its not good to use without aggregate functions
I am using below query for my solution:-
select group_concat("/",col.column_name) as hazards from information_schema.columns
as col inner join db_name.`tbl_occupancy` as oc on col.table_schema="db_name"
and col.table_name = "tbl_occupancy" and col.column_name in (
if(oc.working_people=1,"working_people",""),
if(oc.owner_occupied=1,"owner_occupied",""),
if(oc.students=1,"students",""),
if(oc.dss_referrals=1,"dss_referrals",""),
if(oc.local_authority=1,"local_authority","")
);
You can Use
"concat-ws"
. It does not skip empty strings. However, it does skip any NULL values after the separator and argument.
`mysql> SELECT CONCAT_WS(',','Test',NULL,'1');
output -> 'Test,1'`
You could try like:
SELECT CONCAT_WS("/",
IF(working_people=1,"working_people",""),
IF(owner_occupied=1,"owner_occupied"),
IF(students=1,"students",""),
IF(dss_referrals=1,"dss_referrals",""),
IF(local_authority=1,"local_authority","")) AS result
FROM tbl_occupancy;
Related
I need some help with a query as I don't seem to get my head around it.
First table vacancies:
vac_id
vac_title
vac_location
vac_description
is_deleted
status
Second table vacancies_labels:
vac_id
Label_id
Now I would like to get an output containing all vacancies within a certain location but they also cannot contain the label_id '10' nonetheless of the location.
SELECT `v`.*
FROM `vacancies` AS `v`
LEFT JOIN `vacancies_labels` as `vl` ON `v`.`vacancy_id` = `bl`.`vacancy_id`
WHERE `v`.`vac_location` = 'russia'
AND `v`.`is_deleted` != 1
AND `v`.`status` = 1
AND `vl`.`label_id` NOT IN ('10')
GROUP BY `v`.`vacancy_id`
This results only in the vacancies that have a record in the vacancies_labels table that are not 10. It leaves out however all vacancies that have no records at all in the vacancies_labels table but fit within the location range.
What am I missing here?
Thx!
Using a LEFT JOIN, if the record is not found, then the values will return null. But in your WHERE clause, you have
AND `vl`.`label_id` NOT IN ('10')
as NOT IN doesn't consider nulls you have to do something like...
AND ( `vl`.`label_id` NOT IN ('10') OR `vl`.`label_id` IS NULL)
I want to use mysql to check if a value exists in MySQL Database. If the value exists, I want to do nothing (I don't want to fetch any data). If it does not exist, then I want to set some where conditions.
So this is what I have so far, but its not right. because I still get data fetched, if no where condition is set
SELECT *,
CASE
WHEN ( table_name.record = 'inputrecord')
THEN
//Do nothing because it is found already
ELSE
// since inputrecord does not exist, we will start looking for 'id'
( WHERE table_name.id = '123')
END
FROM table_name
NOTE: In the above example, I have written WHEN ( table_name.record = 'inputrecord') and not WHEN ( table_name.record != 'inputrecord'). This is because I want to only continue the query if the data is not in the table.
Perhaps its better to use the IF function with the EXISTS function, but I am not sure how to do it.
Any help would be great. Right now I get errors
This is not how SQL works.
SQL always returns a collection of rows. It may be empty, sometimes rows may contain NULLs. You have to work out your conditions to filter the collection.
A generic example: say, we have a table of cars with columns (model, color, year), and you would like to find something about the cars in your table:
(* Find all red cars *)
select * from cars where color = 'red'
(* Find all red cars from 1985 *)
select * from cars where color = 'red' and year = 1985
(* Find all colors which exist both in 1990 and 2000 *)
select distinct color from cars A where year=1990 and exists (select 1 from cars B where year=2000 and B.color = A.color)
Please tell exactly what you are trying to achieve
EDIT: this should do it
(* select a record cars = 'Audi' only if cars = 'BMW' is not found in the whole table. otherwise. I do not want to select Audi even if it exists *)
select * from cars where model = 'Audi' and not exists (select 1 from cars where model = 'BMW')
here, IF there are BMWs in your table you'll get 0 rows, otherwise a list of Audis
select *
from table_name
where case when table_name.record <> 'inputrecord'
then table_name.id = '123'
else 1=1
end
you can apply the given condition in your code
when input condition does not match then apply your filter condition.
when input condition match(else case )then retrieve your desired result.
Try This...
SELECT *
CASE
WHEN table_name.record = 'inputrecord' THEN 'Unspecified'
WHEN table_name.id = '123' THEN 'table by id'
END
FROM table_name;
OK.. so I had a post here:
MySQL/PHP/PDO + How to get a row for each (duplicate) entry in IN() clasue?
Apparently... there is no solution. (or so I'm told)..
So is there an alternative solution to using the IN() clause? One that DOES in fact return a row for each item passed in...regardless if its a duplicate entry or not?
I have suggestions about using a (self) JOIN.. or possibly even EXISTS... but I am not clear on how I can go about adjusting my current dynamic query using such suggestions?
$qMarks = str_repeat('?,', count($brandlist) - 1) . '?'; //create '?' mark placeholders for query, remove last comma and replace with '?'
//preserve IN() order
$displayList_sql = "SELECT * FROM $tablename WHERE CONCAT(brandname, ' ', dosage) IN ($qMarks) ORDER BY FIELD(CONCAT(brandname, ' ', dosage),'". trim(implode("','", $brandlist))."')";
$displayList_stmt = $conn->prepare($displayList_sql);
$displayList_stmt->execute($brandlist);//make note of passing in array as param to execute() call
Can this be altered to use a JOIN or EXISTS (anything) so that it returns a row for each item? (which is a dynamically posted array?)
It's not exactly pretty, but you can "convert" your list to a subquery and join that against the actual table you want to query.
SELECT t.stuff
FROM (SELECT 'in item 1' AS item
UNION ALL SELECT 'in item 2'
UNION ALL ...
) AS inList
INNER JOIN $tablename AS t ON inList.item = CONCAT(t.brandname, ' ', t.dosage)
ORDER BY ...
My guess is there is probably some php methods you can use to explode/split the variable you had used to populate the IN list to create the SELECT ... UNION ALL ... subquery.
Worst, most primitive case (in pseudo code), assuming a simple comma-separated list:
theList = "SELECT " + REPLACE(theList, ',', ' AS item UNION ALL SELECT')
If query length becomes an issue, another option is to create a temp table to store the IN list in, and then join against that. (This technique can also sometimes be used to make the query faster; since the temp table can be indexed to help with the join operation.)
I tried to differrent solutions:
First:
SELECT DISTINCT LEFT(EVENTNAAME, 1) FROM EVENTS WHERE DATE >= CURDATE()
AND
SECOND:
SELECT DISTINCT SUBSTRING(EVENTNAAME, 1, 1) FROM EVENTS WHERE DATE >= CURDATE()
Both worked in phpMyAdmin, but in my php-file the result is empty because it can't be stored into a variable.
I have done this:
while ( $row = mysqli_fetch_object ( $result) ) {
$title = $row->EVENTNAME;
}
the var_dump delievers:
object(stdClass)#3 (1) { ["LEFT(EVENTNAME, 1)"]=> string(1) "S" }
but the variable is empty. If I make a select without substring or left the name of the events is fully shown.
But I only want to show the first character of the eventname and use it as title.Therefore I use distinct because if there are more thane one event with the same first letter it delivers only one result.
But this isn't my problem. My problem is how can I store this into a php variable and why does it work if I don't use left or substring with the complete name of the event?
Sorry for bad english and I hope you can help.
Use AS:
SELECT DISTINCT LEFT(EVENTNAME, 1) AS EVENTNAME FROM EVENTS WHERE DATE >= CURDATE()
You need to alias your field names. Once you apply formulates or otherwise create "derivative" values of a field in a query, the field's name is NOT what php will see as a name when it fetches the rows, e.g:
SELECT foo, AVG(foo), SUM(foo), ...
would (not really, just for example) produce
$row['foo'], $row['AVG(foo)'], $row['SUM(foo)']
in your result row.
If you alias the fields, then you have total control over how the field's name appears in the results:
SELECT foo, AVG(foo) AS argle, SUM(foo) AS bargle
^^^^^^^^ ^^^^^^^^^
$row['foo'], $row['argle'], $row['bargle']
I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}