Mysql Query from Two table - mysql

Is it possible to join Two queries of mysql in a query ??
Like:
select * from a + select * from b
So that I can use them in a single php loop.

If they have the same number of columns and the datatypes are the same in each column, then you can use a UNION or UNION ALL:
select *
from a
UNION ALL
select *
from b
If you provide more details about the tables, data, etc, then there might be another way of returning this data.
A UNION will return only the DISTINCT values, while a UNION ALL selects all values.
If this is the route that you need to take, and you still need to identify which table the data came from, then you can always create a column to identify which table the data is from , similar to this:
select *, 'a' TableName
from a
UNION ALL
select *, 'b' TableName
from b
This allows you to distinguish what table the data came from.

I think it is easier creating sql "variables" like:
select varA, varb from TableA, tableB;
and you can just play with values in PHP accessing properties.
That way you can take conditions in the query like:
select varA, varb from TableA, tableB where varA.id = varB.foreingId bla bla...
;)

Related

Get data from two tables using IN clause

What i want to get?
Get id,name,email of the people who have sent me friend_requests.
Two tables i have used on the basis of which i want to get the details
signup -> id,name,email,firmname and a few more columns.
friends_requests ->id,userId,sentRequests,receivedRequests,friends,dates
Please refer to the below two images.
friends requests table
Signup table
What I am trying?
SELECT * FROM signup WHERE signup.id IN
(SELECT sentRequests FROM friends_request WHERE friends_request.userId=46)
This query only gives one record, whereas if i use below query it gives 3 records
SELECT * FROM signup WHERE signup.id IN (47,48,49)
I know why second query is giving three records because of the IN clause and three id's
But this query will also give the same result which is 47,48,49
SELECT sentRequests FROM friends_request WHERE friends_request.userId=46
But why isn't the first query giving three records?
When both the values are same? Then why isn't the result same?
About table friends_requests. Column sentRequests violates 1NF.
if I am right, IN operator gets your information as full string, not as separate ID information.
SELECT *
FROM signup
WHERE signup.id IN ('47,48,49')
what is operator thinks IN ('47,48,49')
what You think IN (47,48,49)
You have to split column value '47,48,49' into returning rows so operator could understand, if you want to use IN operator...
For it to work like you coded it,
SELECT sentRequests FROM friends_request WHERE friends_request.userId=46
would have to give 3 rows with 47,48,49.
Because sentRequests is a string it gives one row with 47,48,49
If you want the 3 values go with:
select * from #signup a where exists (select 1 from friends_request b where ','+sentRequests+',' like ',%'+cast(id as varchar(5))+',%')
try this...
SELECT * FROM signup WHERE id IN (
SELECT
DISTINCT cast(SUBSTRING_INDEX(SUBSTRING_INDEX(sentRequests, ',', n.digit+1), ',', -1) AS signed) sentRequests
FROM friends_request INNER JOIN (
SELECT
0 digit
UNION ALL
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
) n ON LENGTH(REPLACE(sentRequests, ',' , '')) <= LENGTH(sentRequests)-n.digit
WHERE userId = 46
);

mySQL "IN" function to Return the list of not found

Just wanted to ask if this is possible or a way to determine the strings that is not on my table. for example
select name from table_person where name IN('name1','name2','name3')
scenario is name1 and name2 is available on my table but what I want to display is name3, since I want to know what are the things I haven't added.
Just playing around with the worst approach (may be).
Not Recommended
SELECT
suppliedArgTable.name
FROM
(
SELECT 'name1' AS name
UNION
SELECT 'name2'
UNION
SELECT 'name3'
) AS suppliedArgTable
LEFT JOIN
table_person TP ON TP.name = suppliedArgTable.name
WHERE TP.name IS NULL;
http://sqlfiddle.com/#!9/edcbe/2/0
NOT IN combined with reversing your query is a solution.
With the 'list' ('name1','name2','name3') in a (temporary) table e.g. temp_list
and with the data in table_person
the query would be:
select name from temp_list
where name not in (
select distinct(name) from table_person
)
distinct removes doubles. (see also MySQL: Select only unique values from a column)
SELECT name_field
FROM (VALUES('name1'),
('name2'),
('name3'),
('name4'),
('name5')) V(name_field)
EXCEPT
SELECT name_field
FROM name_table
You can use a temporary table to hold a list of all names and find non-matching names with EXCEPT.

MySQL select all from list where value not in table

I cannot create a virtual table for this. Basically what I have, is a list of values:
'Succinylcholine','Thiamine','Trandate','Tridol Drip'
I want to know which of those values is not present in table1 and display them. Is this possible? I have tried using left joins and creating a variable with the list which I can compare to the table, but it returns the wrong results.
This is one of the things I have tried:
SET #list="'Amiodarone','Ammonia Inhalents','Aspirin';
SELECT #list FROM table1 where #list not in (
SELECT Description
FROM table1
);
With only narrow exceptions, you need to have data in table form to be able to obtain those data in your result set. This is the essential problem that all attempts at a solution to this problem run into, given that you cannot create a temporary table. If indeed you can provide the input in any form or format (per your comment), then you can provide it in the form of a subquery:
(
SELECT 'Amiodarone' AS description
UNION ALL
SELECT 'Ammonia Inhalents'
UNION ALL
SELECT 'Aspirin'
)
(Note that that exercises the biggest of the exceptions I noted: you can select scalars directly, without a base table. If you like, you can express that explicitly -- in MySQL and Oracle, at least -- by selecting FROM DUAL.)
In that case, this should work for you:
SELECT
a.description
FROM
(
SELECT 'Amiodarone' AS description
UNION ALL
SELECT 'Ammonia Inhalents'
UNION ALL
SELECT 'Aspirin'
) a
LEFT JOIN table1
ON a.description = table1.description
WHERE table1.description IS NULL
That won't work. the variable's contents will be treated as a monolithic string - one solid block of letters, not 3 separate comma-separated values. The query will be parsed/executed as:
SELECT ... WHERE "'Amio.....rin'" IN (x,y,z,...)
^--------------^--- string
Plus, since you're just doing a sub-select on the very same table, there's no point in this kind of a construct. You could try mysql find_in_set() function:
SELECT #list
FROM table1
WHERE FIND_IN_SET(Description, #list) <> ''

Select from array in MySQL

Is it possible in MySQL to select from a static set of integers? Given an array of integers like 1 and 2, what is the correct syntax in MySQL to do something like:
select
*
from
(values(1),(2))
Which should return one row containing the number 1 and one row containing the number 2.
In other SQL than MySQL (e.g. MSSQL) this is possible. Is there a way to do this in MySQL?
I think you mean something like this?
SELECT 1 UNION SELECT 2 UNION SELECT 3
The only way to create a virtual set in MySQL is using a subquery with UNION. The subquery in the FROM clause creates 3 rows which can be joined with another table:
SELECT foo.*
FROM (
SELECT 1 AS num UNION
SELECT 2 AS num UNION
SELECT 3 AS num
) virtual
LEFT JOIN foo ON foo.num = virtual.num
When you want to use your list of values as a condition for WHERE or ON clause, then the IN() construct may be the right way to go:
SELECT foo.* FROM foo WHERE foo.num IN (1,2,3)
sorry for my english
you can use (IN) like this
SELECT * FROM Table WHERE id IN (1,2,3....)

mysql and or query together

How can i run mysql and or query together instant of separate query.
e.g.:
And query:
select * form tablename where name='A' and password="A" and id='A';
Or query:
select * form tablename where name='A' or password="A" or id='A';
-These are 2 different query,can i make these query together?what is the syntax??
Use parentheses to group the conditions?
SELECT * FROM table WHERE (X and Y or Z) AND (P and Q or F)
Well, you can just union them but, since one is a subset of the other, it's not strictly necessary:
select * from tablename
where name = 'A' and password = 'A' and id = 'A'
union select * from tablename
where name = 'A' or password = 'A' or id = 'A'
That will give you exactly the same results as if you had just run the second query on its own. That will make sense once you realise that every single row from the first query has a name equal to 'A', so it will match the first part of the where clause in the second query.
If you want duplicate rows for those returned in both queries, just use union all instead of union.
If you were using 'A' as just a placeholder and its values are different in the two queries, then you have two approaches. Use a construct like:
... where (name = 'A' and password = 'B' and id = 'C')
or name = 'D' or password = 'E' or id = 'F'
or use the union solution I gave above, something like:
select * from tablename
where name = 'A' and password = 'B' and id = 'C'
union select * from tablename
where name = 'D' or password = 'E' or id = 'F'
(use union all when you know there is no possibility of duplicates between the two queries, - it will save the DBMS the trouble of removing non-existent duplicates - that's not the case with these queries).
The union may give better performance on a DBMS that can hive off the two selects more easily to separate query engines (something that would be more difficult with a single query with a complex where clause). Of course, as will all optimisations, measure, don't guess.
It is not clear what you expect as the result, but my guess is you want a UNION:
SELECT 1 `query`, `name`, `password`, `id`
FROM `tablename` WHERE `name`='A' and `password`='A' and `id`='A'
UNION
SELECT 2 `query`, `name`, `password`, `id`
FROM `tablename` WHERE `name`='A' or `password`='A' or `id`='A'
Note that the first column query in result is required to separate results from the two queries because union of (X and Y) and (X or Y) is always (X or Y).
Use () for such type of conditions
select * form tablename
where name='A' OR password="A" OR id='A' OR
(name='A' AND password="A" AND id='A')
If you want to check for same string as A here then you will get same o/p using following query
select * form tablename
where name='A' OR password="A" OR id='A'
Just combine the conditions with WHERE
SELECT * FROM tablename WHERE (name='A' AND password='A' AND id='A') OR name='A' OR password='A' OR id='A'
The parentheses ensure that the whole AND expressions "validates" only if ALL the containing conditions are true while the rest macthes the OR