MySql - Select from a string concatenated with a comma - mysql

Suppose I have this MySql table:
id
name
city
1
John
NYC
2
Albert
London
3
Joanna
Paris
4
Mike
LA
5
Norton
São Paulo
6
Pedro
Rio de Janeiro
7
August
Chicago
8
Carol
Miami
So I get this string and I would like to filter people with these ids:
"1,3,6,8"
Sometimes the string I got is different: "1,5,4" or "3,6,5,8,1" etc.
Any idea how to achieve this?

You would use a WHERE IN (...) construct in your query:
SELECT *
FROM yourTable
WHERE id IN (1, 3, 6, 8);

#Vanderlei based on your comment I will suggest not using a subquery, but a join because it performs much faster.
select products_table.id,products from products_table
inner join table_people
on products_table.id=table_people.id
WHERE table_people.city = 'London';
Demo: https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/61

Related

How to purposely duplicate specific rows in SELECT statement?

I want to duplicate a specific teacher so that they appear twice in the output of a SELECT statement.
Teacher
Grade
District
Mr. Smith
3rd
West
Mrs. John
4th
South
Mr. Cameron
2nd
North
Mr. Cameron
2nd
North
Kirk Horn
1st
West
Desired result, after duplicating 'Mr. Cameron':
Teacher
Grade
District
Mr. Smith
3rd
West
Mrs. John
4th
South
Mr. Cameron
2nd
North
Mr. Cameron
2nd
North
Mr. Cameron
2nd
North
Mr. Cameron
2nd
North
Kirk Horn
1st
West
What would a SELECT statement look like - without creating a new a table?
I want to do something like this but without the INSERT:
https://dba.stackexchange.com/questions/142414/easiest-way-to-duplicate-rows
If the table is big, and the filter is not selective and backed by an index, then this "trick" avoids a second sequential scan over the table - using PostgreSQL:
SELECT t.* -- or your list of columns
FROM test t
, generate_series(1, CASE WHEN t.teacher = 'Mr. Cameron' THEN 2 ELSE 1 END);
fiddle
It's short syntax for a LATERAL join. See:
What is the difference between a LATERAL JOIN and a subquery in PostgreSQL?
fiddle
If you need more copies, just replace '2' above.
Postgres has a hard time estimating the number of rows to expect with this construct, which may confuse query planning. Stu's variant (doing the same) is slightly more expensive, but easier to estimate for query planning. Syntax needs to be adapted for Postgres:
SELECT teacher, grade, district
FROM test t
JOIN LATERAL (VALUES (1),(2)) x(v) ON v = 1 OR teacher = 'Mr. Cameron';
fiddle
You could use UNION ALL
select Teacher,Grade,District
from test
union all
select Teacher,Grade,District
from test
where Teacher='Mr. Cameron'
order by Teacher;
https://dbfiddle.uk/rBpSL8NW
If you want to force/predict how many duplicate values for Mr. Cameron you will add ,try below query which add only one duplicate value limit 1
(select Teacher,Grade,District
from test
)
union all
(
select Teacher,Grade,District
from test
where Teacher='Mr. Cameron'
limit 1
);
https://dbfiddle.uk/uUX5QD3F

Passing Multiple ids to single parameter in mysql

I have table emloyee with following data.
Id Name Country
1 John USA
2 Smith USA
3 Jack IND
4 Lory UK
5 Miller USA
I want to get result by calling stored procedure like this
call getEmployeeDetailsByCountry('IND,UK');
Result:
Id Name Country
3 Jack IND
4 Lory UK
My Procedure is
select * from employee
where if( (LOCATE(',','IND,USD')>0),
Country in (concat('\'',REPLACE('IND,USD', ',', '\',\''),'\''))
, Country in ('IND,USD'));
Here it replaces 'IND,USD' to 'IND','USD'.
But result is no rows.... Can anyone help me to find..... thank you
Use FIND_IN_SET instead of IN
SELECT *
FROM product
WHERE FIND_IN_SET(country, 'IND,USD');
Try this i think this will solve your problem
Why dont you use a query with a simple IN statement in the where clause?
SELECT * FROM employee WHERE Country IN ('IND', 'UK');

How to sum values of a column of a table?

Book Name Author Name No. of Copies Entry Date
Web Development Er. Gurbax Singh 7 2015-10-07
PHP Mr. Yash Arora 5 2015-10-06
DBMS Mr. Subhash Singla 2 2015-10-30
Data Structure Mr. Balwinder Singh 6 2015-11-14
Multimedia Dr. Latila Bhutani 3 2015-11-23
Graphics Designing Er. Gurpreet Kaur 6 2015-11-23
Note: I want sum of no. of copies
use SUM
SELECT SUM(no_of_copies) AS totalBooks FROM tablename
or Group by sum
SELECT SUM(no_of_copies) AS totalBooks FROM tablename group by BookName

Need to join 2 tables but except some rows in another table in MySQL

I'm not so expert. I need to join 2 tables but except a specific rows whose status is 'Del Edge'. And also duplicate rows are not allowed. I also try to write an query but I think it's not in correct form. For example user 't' log in and he search a name 'Bush', so I need only those data. Any help would be appreciated. Here are the example tables:
links Table:
Id(PK) source target freq
1 Bush Fisher 1
2 Lamburt Bush 6
3 Sam Bush 3
4 Fisher Sam 7
5 Bush Dalai 4
logs Table:
username Id (FK) source target frequency status
t 5 Bush Dalai 4 Add Node
m 8 Dalai Pit 5 Del Edge
t 3 Sam Bush 3 Del Edge
Joining Table should be:
source target frequency
Bush Fisher 1
Lamburt Bush 6
Bush Dalai 4
My Query:
"SELECT source, target, frequency from links, logs
where (links.source=Bush || links.target= Bush) &&
where not exists
(SELECT source, target, frequency FROM logs
WHERE (links.id = logs.id && logs.status=Del Edge)";
The following should do the trick!
SELECT DISTINCT k.source,
k.target,
k.frequency
FROM links k
LEFT JOIN logs g
ON g.id = k.id
WHERE IFNULL(status, '') != 'Del Edge'
AND 'Bush' IN( k.source, k.target )
Hope this helps!
Also, the following fiddle demonstrates that the above answer is, in fact, correct: http://sqlfiddle.com/#!2/9753f/5

Subquery in Access

I have 2 tables in Access with these fields
Student:
ID(PK) Name Family Tel
Lesson:
ID StudentRef(FK(Student)) Name Score
Imagine we have these records
Student :
1 Tom Allen 09370045230
2 Jim leman 09378031380
Lesson:
1 1 Math 18
2 1 Geography 20
3 2 Economic 15
4 2 Math 12
How can I write a query that result will be this (2 fields)?
Tom Math : 18 , Geography 20
Jim Economic :15 , Math :12
SELECT s.Name, l.Name, l.Score
INNER JOIN tbl_lessons as l ON s.student_id = l.student_id
FROM tbl_students as s
That won't give you your formatting, but it'll get you the data.
The most tricky part of your problem is how to aggregate strings in your sub-query. MS Access does not have any aggregation function that is applicable to strings (except for Count()) and there is no way to define your own function. This means you can't just get the desired "subject:score , subject:score" concanetation. As long as you can go without you can easily take the solution provided in the answer by Corith Malin.