Mysql query and reordering results - mysql

My SQL query is like this
SELECT `product_code`, `test`
FROM `table_products`
WHERE `product_code` IN ('38986', '222098', '1113426', '3645651', ...)
I would like the results to be ordered as in product_code order shown in query and also when there is no matching for that product_code in table, I would like to add an empty line in SQL result.

There (probably) is no other way except that you express the values as rows:
SELECT codelist.code, table_products.whatever
FROM (
SELECT 38986 AS code, 1 AS sort UNION ALL
SELECT 222098, 2 UNION ALL
SELECT 1113426, 3 UNION ALL
SELECT 3645651, 4
) AS codelist
LEFT JOIN table_products ON codelist.code = table_products.product_code
ORDER BY codelist.sort
The LEFT JOIN will give you the code number and empty right hand side row if there is no match. ORDER BY sort will sort the products in the desired order.

You can have the reference product code values in another table and use right outer join
eg)
create table Test(id integer, title varchar(100));
create table ref(idtosee integer);//reference table
insert into ref(idtosee) values(1);
insert into ref(idtosee) values(4);
insert into Test(id, title) values(1, "Hello");
insert into Test(id, title) values(2, "sHello");
select id,title,idtosee from Test right outer join ref on id=idtosee;

Related

Delete all duplicate rows in mysql

i have MySQL data which is imported from csv file and have multiple duplicate files on it,
I picked all non duplicates using Distinct feature.
Now i need to delete all duplicates using SQL command.
Note i don't need any duplicates i just need to fetch only noon duplicates
thanks.
for example if number 0123332546666 is repeated 11 time i want to delete 12 of them.
Mysql table format
ID, PhoneNumber
Just COUNT the number of duplicates (with GROUP BY) and filter by HAVING. Then supply the query result to DELETE statement:
DELETE FROM Table1 WHERE PhoneNumber IN (SELECT a.PhoneNumber FROM (
SELECT COUNT(*) AS cnt, PhoneNumber FROM Table1 GROUP BY PhoneNumber HAVING cnt>1
) AS a);
http://sqlfiddle.com/#!9/a012d21/1
complete fiddle:
schema:
CREATE TABLE Table1
(`ID` int, `PhoneNumber` int)
;
INSERT INTO Table1
(`ID`, `PhoneNumber`)
VALUES
(1, 888),
(2, 888),
(3, 888),
(4, 889),
(5, 889),
(6, 111),
(7, 222),
(8, 333),
(9, 444)
;
delete query:
DELETE FROM Table1 WHERE PhoneNumber IN (SELECT a.PhoneNumber FROM (
SELECT COUNT(*) AS cnt, PhoneNumber FROM Table1 GROUP BY PhoneNumber HAVING cnt>1
) AS a);
you could try using a left join with the subquery for min id related to each phonenumber ad delete where not match
delete m
from m_table m
left join (
select min(id), PhoneNumber
from m_table
group by PhoneNumber
) t on t.id = m.id
where t.PhoneNumber is null
otherwise if you want delete all the duplicates without mantain at least a single row you could use
delete m
from m_table m
INNER join (
select PhoneNumber
from m_table
group by PhoneNumber
having count(*) > 1
) t on t.PhoneNumber= m.PhoneNumber
Instead of deleting from the table, I would suggest creating a new one:
create table table2 as
select min(id) as id, phonenumber
from table1
group by phonenumber
having count(*) = 1;
Why? Deleting rows has a lot of overhead. If you are bringing the data in from an external source, then treat the first landing table as a staging table and the second as the final table.

getting data from three different table and inserting it into new table

I have three tables with contents, now i want to get them and add it into new table but am having this sql error "Column count doesn't match value count at row 1"
here is the sql query.
insert into compare_year(yeara,yearb,yearc,data)
SELECT yeara
FROM table_1
UNION ALL
SELECT yearb, data
FROM table_2
UNION ALL
SELECT yearc
FROM table_3
below is how i created the tables
create table table_1(id int primary key auto_increment,yeara varchar(100));
create table table_2(id int primary key auto_increment,yearb varchar(100),data varchar(100));
create table table_3(id int primary key auto_increment,yearc varchar(100));
my new table is now
create table compare_year(id int primary key auto_increment,yeara varchar(100),yearb varchar(100),yearc varchar(100),data varchar(100))
please can someone help me. thanks
Note:when you union select queries,the number of columns should be equal.
and also you cannot insert mutiple select columns into a single row of another.
My solution will be like:
if three table contain same id,then you can do like this
insert into compare_year(yeara,yearb,yearc,data)
SELECT T1.yeara,T2.yearb,T3.yearc,T2.data
FROM table_1 T1
left Join table_2 T2 on T2.Id = T1.Id
left Join table_3 T3 on T3.Id = T2.Id
It looks like what you want is a JOIN rather than a UNION. When you union two select statements, they must have the same number of fields in the SELECT. For example,
insert into compare_year(yeara)
SELECT yeara
FROM table_1
UNION ALL
SELECT yearb AS yeara
FROM table_2
UNION ALL
SELECT yearc AS yeara
FROM table_3
would be acceptable syntactically. If you want to join the tables,
INSERT INTO compare_year(yeara, yearb, yearc, data)
SELECT table_1.yeara, table_2.yearb, table_3.yearc, table_2.data
FROM table_1, table_2, table_3
but note that this is full cartesian product of the tables. It's likely you want some conditionals as well in a WHERE clause. It's also worth noting that the order of the select cause is what's important for the INSERT, not the field names.

Perform a INSERT .. SELECT in MySQL with derived tables

I'm trying to insert the results from a join query into another table.
INSERT INTO temp(
SELECT b.id, b.number, b.attempt FROM(
SELECT number FROM duplicate_numbers)a
JOIN calls b ON b.number=a.number));
The join query on its own without the INSERT INTO clause works fine and returns a dataset. But the above query gives SQL syntax error
Change query syntax like this:
CREATE TABLE temp (`id` int, `number` int, `attempt` int);
INSERT INTO temp (`id`, `number`, `attempt`)
SELECT b.id, b.number, b.attempt FROM (
SELECT number FROM duplicate_numbers
) a
JOIN calls b ON b.number=a.number
Working demo: http://sqlfiddle.com/#!9/24f9f

One Row to Match Them All

So I have a situation where I have two tables. One is the base table (called _Keys in this example), with a unique primary key. Then there is another table with multiple rows of a data for each id in _Keys (this second table is Extra).
I need to select the largest value for each primary key in _Keys from Extra. I have made an SQLFiddle to model the problem here.
This is the query I'm currently using, but the issue is that it will only select one value for the Extra table, not one value per row.
Select * from _Keys
LEFT JOIN
(Select * from Extra ORDER BY value2 DESC LIMIT 1) as e
ON e.id = _Keys.id;
For my example SQL Fiddle I used this database schema:
CREATE TABLE _Keys(id int, value int);
INSERT INTO _Keys (id, value) VALUES (1, 5),(2, 3),(3, 4);
CREATE TABLE Extra(id int, value2 int);
INSERT INTO Extra (id, value2) VALUES (1, 3),(1, 1),(2, 4),(2, 6),(3, 3),(3, 5);
Basically my result is here. Only the first row from the _Keys table gets its data from the second table.
In MySQL, how can I achieve selecting one row from Extras for each row in _Keys?
I believe I understand what you are trying to do but I'm not sure.
You are getting NULL values because of the LIMIT, it only returns the first row. You also need to use GROUP BY.
To get the largest value, your can use MAX.
Try this.
SELECT * from _Keys
LEFT JOIN
(SELECT id, MAX(value2) AS value2 FROM Extra GROUP BY id) as e
ON e.id = _Keys.id;
Your joined table Select * from Extra ORDER BY value2 DESC LIMIT 1 will contain only one row because of LIMIT. Try this:
Select * from _Keys
LEFT JOIN
(Select id, max(value2) from Extra group by id) as e
ON e.id = _Keys.id;
You can try this query with better performance :
SELECT k.id, MAX(e.value2) AS value2
FROM _Keys k
INNER JOIN Extra e
ON (k.id = e.id)
GROUP BY k.id;

Inserting values from two tables into a new table

I ran this query:
Insert into transaction(matric,surname,other,level,bk_id,bk_title)
values(
(select matric,surname,others,level from member_master),
(select isbn,bk_title from book_master)
)
but I got this error:
column count doesn't match value count at row 1
You have to use the same columns which you have mentioned in the insert statement. Presently your insert statement mentions matric,surname,other,level,bk_id,bk_title columns whereas the columns in select are different. Try like this:
Insert into transaction(matric,surname,other,level,bk_id,bk_title)
values
(select m.matric,m.surname,m.others,m.level,b.isbn,b.bk_title
from member_master m inner join book_master b on m.id = b.id)
Assuming that the two tables are linked with the ID column