sql stored procedure with out duplicates name - mysql

How can I create a query to SELECT ALL DB WITHOUT duplicates
Like (old DB that is no longer in use c,f,g. basically if it does have eur and has an original name than it is relevant):
a
b
c
ceur
d
f
feur
g
geur
I need it to be like:
a
b
ceur
d
feur
geur
Many thanks...

SELECT DISTINCT
is what you're looking for. See more here.
For instance, let's say you have a table that contains the following rows:
name, city, address, country.
You now wish to get the countries that has been stored, without duplicates. Multiple people might come from the same country, and so the table would most likely have duplicate entries of that country.
How you achieve this is by using the SELECT DISTINCT.
Example:
SELECT DISTINCT country FROM table_name;
What this will do is retreive the country row without duplicates. That way, you can see which countries are actually stored in that table without duplicates.
If you have multiple databases (I don't know if that's what you were getting at), then you will need to perform a JOIN on the relevant tables, given you have access to them all. I would recommend doing a LEFT JOIN if you are to join more than just 1 extra table.
Example:
SELECT DISTINCT table_name.row_name, table_name.row_name2, table_name.row_name3
FROM table_name
LEFT JOIN table_name2 ON table_name.row_name = table_name2.row_name
LEFT JOIN table_name3 ON table_name2.row_name = table_name3.row_name
[...]
WHERE table.row_name = 'value';

Can you query information_schema.TABLES and distinct in the select, plus a predicate to filter out whatever you don't want?

You can do:
select t.*
from t
where name like '%eur'
union all
select t.*
from t
where not like '%eur' and
not exists (select 1 from t t2 where t2.name = concat(t.name, 'eur');

Related

Save the intermediate result of SQL query

I am wondering if there is any way to save the intermediate result or tables in SQL. For example assume you have two different SQL statements that in the first statement you join two tables, then you want to see how many rows the resulting table has. I know there are many ways to do this but I am interested in seeing how this can be done sequentially. Consider the following example:
select * from order_table left join customer_table on order_table.id = customer_table.id
Then I want to see count of number of rows (as an easy example)
select count(*) from table
But I do not know what this table should be. How may I save the result of above query in some logical table or how to refer to what was created before in SQL.
You can use WITH like below:
WITH resultTable as ( select * from order_table left join customer_table on order_table.id = customer_table.id )
select count(*) from resultTable
For this particular example you can simply wrap the original query in a sub-query:
select count(*)
from (
select *
from order_table
left join customer_table on order_table.id = customer_table.id
) as x
If you want to store the result in a physical table (temporary or permanent) then the procedure varies for each rdbms. In SQL Server for example you would use SELECT INTO:
select *
into #temp_table
from order_table
left join customer_table on order_table.id = customer_table.id
you can also use CTE. for your question it will be:
;
with table1 as (
select * from order_table
left join customer_table on order_table.id = customer_table.id
)
select count(*) from table1
GO

How to do a join on 2 tables, but only return the data for one table?

I am not sure if this is possible. But is it possible to do a join on 2 tables, but return the data for only one of the tables. I want to join the two tables based on a condition, but I only want the data for one of the tables. Is this possible with SQL, if so how? After reading the docs, it seems that when you do a join you get the data for both tables. Thanks for any help!
You get data from both tables because join is based on "Cartesian Product" + "Selection". But after the join, you can do a "Projection" with desired columns.
SQL has an easy syntax for this:
Select t1.* --taking data just from one table
from one_table t1
inner join other_table t2
on t1.pk = t2.fk
You can chose the table through the alias: t1.* or t2.*. The symbol * means "all fields".
Also you can include where clause, order by or other join types like outer join or cross join.
A typical SQL query has multiple clauses.
The SELECT clause mentions the columns you want in your result set.
The FROM clause, which includes JOIN operations, mentions the tables from which you want to retrieve those columns.
The WHERE clause filters the result set.
The ORDER BY clause specifies the order in which the rows in your result set are presented.
There are a few other clauses like GROUP BY and LIMIT. You can read about those.
To do what you ask, select the columns you want, then mention the tables you want. Something like this.
SELECT t1.id, t1.name, t1.address
FROM t1
JOIN t2 ON t2.t1_id = t1.id
This gives you data from t1 from rows that match t2.
Pro tip: Avoid the use of SELECT *. Instead, mention the columns you want.
This would typically be done using exists (or in) if you prefer:
select t1.*
from table1 t1
where exists (select 1 from table2 t2 on t2.x = t1.y);
Although you can use join, it runs the risk of multiplying the number of rows in the result set -- if there are duplicate matches in table2. There is no danger of such duplicates using exists (or in). I also find the logic to be more natural.
If you join on 2 tables.
You can use SELECT to select the data you want
If you want to get a table of data, you can do this,just select one table date
SELECT b.title
FROM blog b
JOIN type t ON b.type_id=t.id;
If you want to get the data from two tables, you can do this,select two table date.
SELECT b.title,t.type_name
FROM blog b
JOIN type t ON b.type_id=t.id;

Quick SELECT WHERE IN like with flag

I have a list of ids and need to check whether user with id is in DB or not in one SELECT. Like SELECT WHERE IN (). But SELECT WHERE IN () doesn't suit my needs, I need in one SELECT distinguish those ids that are in table, and those that are not, not using any loops like multiple SELECTS. Any ideas are welcome!
I'm not sure if this is what you need, but I guess you have table 1 which contains a lot of IDs, and you would like to see which ones occur in table 2 and which ones don't?
select T1.ID, count(*) 'Times of occurrences in T2'
from table 1 T1
left outer join table 2 T2
ON T1.ID = T2.ID
group by T1.ID
You should provide more details. Would it be a single query so a list could be hardcoded into query or you want to find general solution for any list of ids provided? How long is your list?
For single query and not very long list you can use union. On example:
SELECT some_value, EXISTS( SELECT 1 FROM tableName WHERE user_id = some_value )
UNION ALL
SELECT other_value, EXISTS( SELECT 1 FROM tableName WHERE user_id = other_value )
UNION ALL
SELECT other_value2, EXISTS( SELECT 1 FROM tableName WHERE user_id = other_value2 )
UNION ALL
.....
If your list of ids can vary and/or consists of thousands of records it is impossible. In list you have columnar layout and you want to change it to row-level results. In MsSQL there are PIVOT, UNPIVOT clauses which can do that. In MySQL such transformation without explicit unions are impossible.

Eliminating duplicates from SQL query

What would be the best way to return one item from each id instead of all of the other items within the table. Currently the query below returns all manufacturers
SELECT m.name
FROM `default_ps_products` p
INNER JOIN `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
I have solved my question by using the DISTINCT value in my query:
SELECT DISTINCT m.name, m.id
FROM `default_ps_products` p
INNER JOIN `default_ps_products_manufacturers` m ON p.manufacturer_id = m.id
ORDER BY m.name
there are 4 main ways I can think of to delete duplicate rows
method 1
delete all rows bigger than smallest or less than greatest rowid value. Example
delete from tableName a where rowid> (select min(rowid) from tableName b where a.key=b.key and a.key2=b.key2)
method 2
usually faster but you must recreate all indexes, constraints and triggers afterward..
pull all as distinct to new table then drop 1st table and rename new table to old table name
example.
create table t1 as select distinct * from t2; drop table t1; rename t2 to t1;
method 3
delete uing where exists based on rowid. example
delete from tableName a where exists(select 'x' from tableName b where a.key1=b.key1 and a.key2=b.key2 and b.rowid >a.rowid) Note if nulls are on column use nvl on column name.
method 4
collect first row for each key value and delete rows not in this set. Example
delete from tableName a where rowid not in(select min(rowid) from tableName b group by key1, key2)
note that you don't have to use nvl for method 4
Using DISTINCT often is a bad practice. It may be a sing that there is something wrong with your SELECT statement, or your data structure is not normalized.
In your case I would use this (in assumption that default_ps_products_manufacturers has unique records).
SELECT m.id, m.name
FROM default_ps_products_manufacturers m
WHERE EXISTS (SELECT 1 FROM default_ps_products p WHERE p.manufacturer_id = m.id)
Or an equivalent query with IN:
SELECT m.id, m.name
FROM default_ps_products_manufacturers m
WHERE m.id IN (SELECT p.manufacturer_id FROM default_ps_products p)
The only thing - between all possible queries it is better to select the one with the better execution plan. Which may depend on your vendor and/or physical structure, statistics, etc... of your data base.
I think in most cases EXISTS will work better.

Select from multiple tables without a join?

What is the easiest way to select data from two tables and rather than join them, have them appear as separate rows. Both tables have similar or matching fields and I want to run some aggregate function on them such as avg all the rows that occurred in the same month, from both tables.
for example I have two tables, one that is shows transactions from one system and another with transactions from a different system. Is there a way to grab all the transactions from both tables as separate rows? if table 1 had twenty records and table 2 have thirty records, I'd like there to be 50 rows on the return.
You could try something like this:
SELECT ...
FROM (
SELECT f1,f2,f3 FROM table1
UNION
SELECT f1,f2,f3 FROM table2
)
WHERE ...
You could try this notattion:
SELECT * from table1,table2
More complicated one :
SELECT table1.field1,table1.field2, table2.field3,table2.field8 from table1,table2 where table1.field2 = something and table2.field3 = somethingelse
Such queries are usually called "implicit JOINs" and Explicit vs implicit SQL joins asks how both compare. In some cases implicit query execution planning is identical to explicit JOINs.
The UNION ALL operator may be what you are looking for.
With this operator, you can concatenate the resultsets from multiple queries together, preserving all of the rows from each. Note that a UNION operator (without the ALL keyword) will eliminate any "duplicate" rows which exist in the resultset. The UNION ALL operator preserves all of the rows from each query (and will likely perform better since it doesn't have the overhead of performing the duplicate check and removal operation).
The number of columns and data type of each column must match in each of the queries. If one of the queries has more columns than the other, we sometimes include dummy expressions in the other query to make the columns and datatypes "match". Often, it's helpful to include an expression (an extra column) in the SELECT list of each query that returns a literal, to reveal which of the queries was the "source" of the row.
SELECT 'q1' AS source, a, b, c, d FROM t1 WHERE ...
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2 JOIN t3 ON ...
UNION ALL
SELECT 'q3', '1', '2', buckle, my_shoe FROM t4
You can wrap a query like this in a set of parenthesis, and use it as an inline view (or "derived table", in MySQL lingo), so that you can perform aggregate operations on all of the rows.
SELECT t.a
, SUM(t.b)
, AVG(t.c)
FROM (
SELECT 'q1' AS source, a, b, c, d FROM t1
UNION ALL
SELECT 'q2', t2.fee, t2.fi, t2.fo, 'fum' FROM t2
) t
GROUP BY t.a
ORDER BY t.a
If your question was this -- Select ename, dname FROM emp, dept without using joins..
Then, I would do this...
SELECT ename, (SELECT dname
FROM dept
WHERE dept.deptno=emp.deptno)dname
FROM EMP
Output:
ENAME DNAME
---------- --------------
SMITH RESEARCH
ALLEN SALES
WARD SALES
JONES RESEARCH
MARTIN SALES
BLAKE SALES
CLARK ACCOUNTING
SCOTT RESEARCH
KING ACCOUNTING
TURNER SALES
ADAMS RESEARCH
ENAME DNAME
---------- --------------
JAMES SALES
FORD RESEARCH
MILLER ACCOUNTING
14 rows selected.
You should try this
SELECT t1.*,t2.* FROM t1,t2
SELECT * from table1
UNION
SELECT * FROM table2
Union will fetch data by row not column,So If your are like me who is looking for fetching column data from two different table with no relation and without join.
In my case I am fetching state name and country name by id. Instead of writing two query you can do this way.
select
(
select s.state_name from state s where s.state_id=3
) statename,
(
select c.description from country c where c.id=5
) countryname
from dual;
where dual is a dummy table with single column--anything just require table to view
select 'test', (select name from employee where id=1) as name, (select name from address where id=2) as address ;
In this case we are assuming that we have two tables:
SMPPMsgLogand SMSService with common column serviceid:
SELECT sp.SMS,ss.CMD
FROM vas.SMPPMsgLog AS sp,vas.SMSService AS ss
WHERE sp.serviceid=5431
AND ss.ServiceID = 5431
AND Receiver ="232700000"
AND date(TimeStamp) <='2013-08-07'
AND date(TimeStamp) >='2013-08-06' \G;
you can try this works always for me
query="SELECT * from tableX,tableY,table8";