I am trying to get a result where a single column id is like a comma separated columns, my two table are as follows:
Room Location Table
Events Table
User Table
My query is
$sql=" SELECT users.*, events.*, room_location.*
FROM events
INNER JOIN room_location ON events.event_room = room_location.location
INNER JOIN users ON room_location.user_loc_id = users.userlocationaccess
WHERE room_location.user_loc_id LIKE '%1,2%'";
$result = $conn->query($sql);
The query above works if I use single id in in the users->userGroupLocID.
How do I amend my query to work so it find if the id is like my comma separated columns?
You can search a CSV field using FIND_IN_SET(str,strlist) function.
Example:
mysql> SELECT FIND_IN_SET('b','a,b,c,d');
-> 2
Documentation Says:
Returns a value in the range of 1 to N if the string str is in the
string list strlist consisting of N substrings. A string list is a
string composed of substrings separated by “,” characters.
You can pass users location id to find in the column userGroupLocID
select find_in_set( location_id_in_search, replace( userGroupLocID, ' ', '' ) )
from table_name;
Related
Trying to figure out if there is a MySQL query for the following scenario:
Database example
id---fruit------date
01---apple------1990-01-01
02---banana-----2020-01-01
03---orange-----2021-02-03
04---apple------1999-12-12
05---pear-------2009-01-02
06---apple------2008-09-18
07---banana-----2007-11-12
I want a query to return all rows but for rows with the same fruit only one occurence and preferably the occurence with the latest date. So based on the above the query would return:
id---fruit------date
02---banana-----2020-01-01
03---orange-----2021-02-03
05---pear-------2009-01-02
06---apple------2008-09-18
SELECT * FROM `table_name`
WHERE
id
IN
(
SELECT SUBSTRING_INDEX(temp,"|",1) `id` FROM
(
SELECT *,GROUP_CONCAT(id ORDER BY DATE DESC SEPARATOR "|") temp FROM `table_name`
GROUP BY fruit
)
AS dbx
)
Explaination:
Group_concat Id with Order by date. At this time I user separator "|"
Get position of that char to return latest ID
Select again from that table
I have a php page that is submitted a search string which is separated by commas. I have to search the database to check if the search terms are first names or last names, as well as if they match any of the interests/skills/hobbies in my interest/skill/hobby tables.
After I explode the string by ", " I first make the query to search for names which is
SELECT *
FROM Users
WHERE FirstName = 'term1'
OR FirstName = 'term2'
OR LastName = 'term1'
OR LastName = 'term2'.
Then the query for searching by interests skills and hobbies and the users that have those tags is this
SELECT user_id from (
(SELECT *
from UserInterests
WHERE interest_id = interestid1
OR interest_id = interestid2
)
UNION ALL
(SELECT *
from UserSkills
WHERE skill_id = skillid1
OR skill_id = skillid2
)
UNION ALL
(SELECT *
from UserHobbies
WHERE hobby_id = hobbyid1
OR hobby_id = hobbyid2
)
) a
GROUP BY user_id
ORDER BY count(*) DESC
What I want to do is be able to search something like John, Rockclimbing, Dancing. Then the user who matches the most of those terms would be shown first.
I tried combining the two in many different ways some of which don't even error, but I don't get any results in my ui.
UserInterests/UserSkills/UserHobbies are just two column tables with user_id and interest/skill/hobby_id
Let's say I have the following table, called test:
Executing the query SELECT DISTINCT category FROM test ORDER BY category; will output:
When changing a value as follows:
…and calling the query SELECT DISTINCT category FROM test ORDER BY category; again, I'll get:
But I want to get the following instead:
Is there a way to do this in SQL? Or should I do this directly in my PHP?
You should have 3 tables here. One will hold the the categories, the other one will hold the items and the final one will hold the relations between categories and items (it is also known as associative table):
categories: id name
items: id name
categories_items: category_id item_id
Your query in this case will become:
SELECT id, name
FROM categories
ORDER BY name;
If you want to get all items from a category you could do:
SELECT id, name
FROM items
JOIN categories_items
ON items.id = categories_items.item_id
AND categories_items.category_id = 4;
You should definetely normalize your tables but if you still insist on this table structure, you can try this query:
WITH CatChar(aChar, remain) AS (
SELECT LEFT(category,1), RIGHT(category, LEN(category)-1)
FROM test WHERE LEN(category)>0
UNION ALL
SELECT LEFT(remain,1), RIGHT(remain, LEN(remain)-1) FROM CatChar
WHERE LEN(remain)>0
)
SELECT DISTINCT aChar FROM CatChar
(Assuming your all category names are just one char length, otherwise you should reorganeze LEFT(...) part to split according to your separator)
Good Day!
Is it possible to apply if condition in the query in codeigniter: model?
I have this query in Model:
function activity($id) {
$this->db->select('a.ID, a.activityID, r.roleName');
$this->db->from('activity a');
$this->db->join('role r', 'r.ID = a.activityID');
$this->db->where('a.ID', $id);
$query = $this->db->get();
return $query->result_array();
}
And in my view I want to show the ID and activityID from table activity and also the counter part roleName (from table role) of activityID.
But the tricky part is that the value in activityID is not just a simple INT, like this:
ID ActivityID
1 5,7,9
2 2,4
3
4 10
5 1,6
So I'm thinking to use if condition in the query, like if the activityID value not contains comma (,) it will use join like this: $this->db->join('role r', 'r.ID = a.activityID'); then get the r.roleName.
Example:
ID ActivityID Role Name
4 10 Basketball
But if contains comma (,), it will explode by comma (,) then join like this: $this->db->join('role r', 'r.ID = a.activityID'); but it will output also by roleName with comma in between.
Example:
ID ActivityID Role Name
1 5,7,9 Tennis,Football,Soccer
2 2,4 Volleyball,Chess
Can someone help me with this?
Thanks in advance.
This is very bad idea to have comma separated ids in your column you should first normalize your structure other wise it will lead you more expensive problems,for now you use FIND_IN_SET() ,for having role names also as comma separated you can use GROUP_CONCAT
Be ware of that fact it has a default limit of 1024 characters to concat but it can be increased which is defined in manual
SELECT
a.ID,
GROUP_CONCAT(a.activityID) activityID,
GROUP_CONCAT(r.roleName) roleName
FROM activity a
LEFT JOIN `role` r ON(FIND_IN_SET(r.ID,a.activityID) > 0);
WHERE a.ID = $id
GROUP BY a.ID
For CI use query() function for above query
Please first have a look at Database Normalization
Suppose I have a table Student with two columns
1)roll
2) marks
Now I want to retrieve the mark if it is same for all roll's that are supplied as an argument
How can achieve this with a single query on MySQL?
The roll list is stored in php array variable $intRolls
Here (1,2,3,4,5) you have to pass as Array.Check SQL FIDDLE here
SELECT
marks
FROM students
WHERE roll IN(1,2,3,4,5)
GROUP BY marks
HAVING COUNT( * ) = (SELECT
COUNT(DISTINCT roll)
FROM students
WHERE roll IN(1,2,3,4,5))
What should the query return if there are different marks? This one will return NULL in this case:
SELECT IF( COUNT(mark) > 1, NULL, mark) AS processed_mark
FROM students
WHERE roll IN (coma-separated-list-of-rolls-here)
GROUP BY mark;