SQL Query, query to having single field name from different table - mysql

I have two table with some identical field. (please don't blame the design).
Below only for the example schema
Table A
id
name
phone
keys
Table B
id
name
keys
address
So, i want to query id, name from either table A or B which meet condition 'keys' on single query, with return Field just "ID" and "NAME" no matter it's from tableA or tableB
with simple query
SELECT a.id, a.name, b.id, b.name FROM TABELA as a, TABLEB as b WHERE a.keys = '1' or b.keys = '1'
It return duplicate id, name, id1, name1 to the result field.

Use UNION instead of CROSS JOIN:
SELECT a.id, a.name
FROM TABELA as a
WHERE a.keys = '1'
UNION
SELECT b.id, b.name
FROM TABLEB as b
WHERE b.keys = '1'

use union or union all. Union returns only distinct rows, union all returns all rows
see examples in manual manual on unions
SELECT a.id, a.name FROM TABELA as a WHERE a.keys = '1'
union
SELECT b.id, b.name FROM TABELb as b WHERE b.keys = '1'

You are not actually joining tables, but you just want to combine the result of two different queries. We have UNION SELECT for that:
SELECT id, name FROM tableA
WHERE keys = '1'
UNION SELECT id, name FROM tableB
WHERE keys= '1'
If you want to order the result, you can use above as a subquery.

Related

Check if table a primary key is exist in table b

Table A:
ID, Name, etc.
Table B:
ID, TableA-ID.
SELECT * FROM A;
and I want to return a boolean value in the same result for this condition ( if A.ID Exists in Table B).
There are several ways of achieving what you need. Below are three possibilities. These all differ in execution plans and how database actually wants to execute them so depending on your record count one may be more efficient than the other. It's better if you see it for yourself.
1) Use LEFT JOIN and check if a non-null field from B is not null to ensure the record exists. Then apply DISTINCT clause if relationship is 1:N to only show rows from A without duplicates.
select distinct a.*, b.id is not null as exists_b
from a
left join b on
a.id = b.tablea-id
2) Use exists() function, which will be evaluated for each row being returned from table A.
select a.*, exists(select 1 from b where a.id = b.tablea-id) as exists_b
from a
3) Use a combination of subquery expression EXISTS and it's contradiction in two queries to check if a record has or has not a match within table B. Then UNION ALL to combine both results into one.
select *, true as exists_b
from a
where exists (
select 1
from b
where a.id = b.tablea-id
)
union all
select *, false as exists_b
from a
where not exists (
select 1
from b
where a.id = b.tablea-id
)
select A.*, IFNULL((select 1 from B where B.TableA-ID = A.ID limit 1),0) as `exists` from A;
The above statement will result in a 1, if the key exists, and a 0 if that key does not exist. Limit 1 is important if there are multiple records in B

SQL Table Counting and Joining

I have Table A, Column 1.
This table has values such as:
1
2
3
3
4
4
4
5
I have Table B, Column 2.
Which lists certain values, like:
1
3
4
I need a query to Count each unique value in Table A, but ONLY if that value is present in Table B.
So with the above, the end result would be:
1 has a quantity of 1,
3 has a quantity of 2,
and 4 has a quantity of 3.
My only problem is that I do not have this ability. Any help out there?
Based on your question, something like the following should solve your problem.
select b.column1,
count(a.column2)
from tableb as b
inner join tablea as a on b.column1 = a.column2
group by b.column1
Since you wanted only records which are in both tables, I am using an inner join. Then I am just grouping by the ID found in tableb, and getting the count of rows in tablea.
Let me know if you have any problems.
For more information regarding inner join, see : http://www.w3schools.com/sql/sql_join_inner.asp, and for group by, see : http://www.w3schools.com/sql/sql_groupby.asp
I would use an INNER JOIN query with GROUP BY aggregate function
SELECT a.column1,
count(a.column1) as total
FROM tablea a
INNER JOIN tableb b
ON a.column1 = b.column2
GROUP BY a.column1
SELECT column1,COUNT(column1)
FROM table1
WHERE column1 IN
(SELECT DISTINCT column2 FROM table2)
GROUP BY column1
Try this
MsSql
Select Distinct Column1,Count(Column1) Over (Partition by Column1)
From Table1
Where Column1 IN (Select Column2 From Table2)
Fiddle Demo
MySQl
Select Column1,Count(Column1)
From Table1
Where Column1 IN (Select Column2 From Table2)
group by column1
Fiddle Demo

What is wrong with my SQL query which uses Joins and Unions?

What's wrong with my sql query? I am trying to use a Join and at the same time a UNION to get all table from another table while joining other tables together based on a relationship ..
However I get the following error:
"The used SELECT statements have a different number of columns"
My query:
SELECT a.ESN, a.UnixTime, a.Payload, a.Timestamp
,b.AlarmingStatus
,b.STxModel
,c.GroupID
FROM STxMessage a
JOIN STx b ON b.ESN = a.ESN
JOIN GroupInfo c ON b.GroupID = c.GroupID
WHERE b.STxModel = 190
AND a.AlarmsChecked="y"
AND c.AlertsMasterSwitch="on"
UNION ALL
SELECT d.ESN , d.UnixTime, d.Payload, d.Timestamp FROM STxMessageArchive d
The error message says it all.
When using UNION, the columns return by the combined SELECT statement must be the same, eg.
SELECT col1, col2, col3 FROM table1
UNION
SELECT col1, col2, col3 FROM table2
if the columns do not match, you can still combine it provided that you have to provide dummy data for the column, eg
SELECT col1, col2, col3 FROM table1
UNION
SELECT col1, col2, '' AS col3 FROM table2
so in your query, it should look like this
SELECT a.ESN, a.UnixTime, a.Payload, a.Timestamp ,
b.AlarmingStatus, b.STxModel, c.GroupID
FROM STxMessage a
INNER JOIN STx b
ON b.ESN = a.ESN
INNER JOIN GroupInfo c
ON b.GroupID = c.GroupID
WHERE b.STxModel = 190 AND
a.AlarmsChecked="y" AND
c.AlertsMasterSwitch="on"
UNION ALL
SELECT d.ESN, d.UnixTime, d.Payload, d.Timestamp,
NULL AS AlarmingStatus, NULL AS STxModel, NULL AS GroupID
FROM STxMessageArchive d
hi this are the extra columns in your first query
,b.AlarmingStatus
,b.STxModel
,c.GroupID
you need this same columns in second query to do union or you need to remove this column to do union operation
Your first query is selecting 7 columns where as the second query is only selecting 4. You need to make sure the second query is selecting the same number of columns as the first to make the Union All work.
SELECT a.ESN, a.UnixTime, a.Payload, a.Timestamp
,b.AlarmingStatus
,b.STxModel
,c.GroupID
FROM STxMessage a
JOIN STx b ON b.ESN = a.ESN
JOIN GroupInfo c ON b.GroupID = c.GroupID
WHERE b.STxModel = 190
AND a.AlarmsChecked="y"
AND c.AlertsMasterSwitch="on"
UNION ALL
SELECT d.ESN , d.UnixTime, d.Payload, d.Timestamp, 'null' as AlarmingStatus,
'null' as STxModel, 'null' as GroupID FROM STxMessageArchive d
As the error says, the first part has 7 columns, and the second part has only 4. An unions needs to have the same columns on both sides. Either remove
b.AlarmingStatus ,b.STxModel ,c.GroupID
from the first part, or add (even bogus) columns in the second part.

need to show only the duplicate value in sql

i have table as
id----name----roll-----class
1----ram-------1-----2
2----shyam-----2-----3
3----ram-------1-----3
4----shyam-----2-----3
5----ram-------1-----2
6----hari------1-----5
i need to find the the duplicate row only that have common name, roll, class. so the expected result for me is.
id----name----roll-----class
1----ram-------1-------2
2----shyam-----2-------3
4----shyam-----2-------3
5----ram-------1-------2
i tried to get from the query below but here only one field is supported. i need all three field common. Please do help me in this. thanks
SELECT *
FROM table
WHERE tablefield IN (
SELECT tablefield
FROM table
GROUP BY tablefield
HAVING (COUNT(tablefield ) > 1)
)
You can use count() over().
select id, name, roll, class
from (select id, name, roll, class,
count(*) over(partition by name, roll, class) as c
from YourTable) as T
where c > 1
order by id
https://data.stackexchange.com/stackoverflow/query/63720/duplicates
this will retun only the duplicate entry one time:
select t.id, t.name, t.roll, t.class
from table t
inner join table t1
on t.id<t1.id
and t.name=t1.name
and t.roll = t1.roll
and t.class=t1.class
this will return what you require:
select distinct t.id, t.name, t.roll, t.class
from table t
inner join table t1
on t.name=t1.name
and t.roll = t1.roll
and t.class=t1.class
I'd suggest something like this
SELECT A.* FROM
Table A LEFT OUTER JOIN Table B
ON A.Id <> B.Id AND A.Name = B.Name AND A.Roll = B.Roll AND A.Class = B.Class
WHERE B.Id IS NOT NULL
Something like that should work (I did not test though):
select a1.*
from table a1, a2
where (a1.id != a2.id)
and (a1.name == a2.name)
and (a1.roll== a2.roll)
and (a1.class== a2.class);
It seems there are several proprosals here. If it is a query that you'll use in your code, beware of the cost of the queries. Try an 'explain' with your database.

union two tables and order by a common field like name which is present in both the tables

I have two tables a and b which has a field name in it.
I need to list the data from these two tables. I thought of using union but in the result list data from the first table appears and then followed by the second.
what i want is to order by the field name so the result should be a mixed up of two tables in the order of name that is order by name.
select slug, name, 1 as mt
from tablea
union
select slug, name, 0 as mt
from tableb
order
by name;
The above is working well for me. will there be any complications in the result of this?
Suppose your query is
SELECT field1 FROM TABLE1 WHERE 1
UNION SELECT field1 FROM TABLE2 WHERE 1
u can make it a subquery like this
SELECT * FROM (SELECT field1 FROM TABLE1 WHERE 1
UNION SELECT field1 FROM TABLE2 WHERE 1) AS `result` ORDER BY `result`.`field1`
Or, you could use a Join query such as:
SELECT tablea.firstname, tablea.middlename, tablea.lastname, tableb.phone
FROM tablea, tableb
WHERE tablea.ID = tableb.ID
Then, you could sort the result however you like.