Recursive self join for chain counting - mysql

I have a table with 2 columns, each column is a FK to the same entity
Col1 and col2 are unique
I'm looking to create a query that recursively attempt a self join from Col2 -> Col1 based upon the IDs being the same on Col2 and Col1 between different rows
I cannot fathom this further than:
select *
from table as t1
join table as t2 on t1.col2 = t2.col1
That query only does a single join but i'd like to keep joining for as long as it is successful to retrieve a sum of successful joins
It's not possible for me to manually write the joins because there could potentially be none, one or many joins

You can use recursive cte to achieve this.
Sample example
With recursive cte(id) as
(Select 1 as id from dual
Union all
Select id +1 from cte where id < 10)
Select * from cte;
Here values will recusively generate untill it reaches value of 10.

Related

Create a new variable in SQL by groupby

I have 2 sql table as follows:
First table t1:
Second table t2:
I need to calculate the count of "Number" column based on "Name" column from t1 and merge it with t2.
I wrote following code. But it seems not working
select *
from (
select Name, count(Number) as count
from t1
group by Name ) as a
join ( select *
from t2 ) as b
on a.Name = b.Name;
Can any one figure out what is wrong ? Thank you very much
I think you want to use SUM() instead of COUNT().
Because SUM() sums some integers, while COUNT() counts number of occurencies.
And as also stated in the comments, multiple columns with same names will create conflicts, so you have to select the wanted columns explicit (that is usually a good idea anyway).
You could obtain your wanted endgoal by this query:
select
SUM(Number),
t1.Name,
(select val1 FROM t2 WHERE t2.Name = t1.Name LIMIT 1) as val1
FROM t1
GROUP BY t1.Name
Example in sqlfiddle: http://sqlfiddle.com/#!9/04dddf/7

Is there any syntax for adding new record between two records in sql table?

Please suggest how to insert new record between two records.
Id 3 of record/row is missed between id 2 and 4 in sql table.
SQL tables are unordered sets. You cannot add a record "between two records", because there is no order to the records. Even if your queries seem to return the rows in some order, it's completely arbitrary, and unless you have an explicit order by clause could very well change.
In other words - you should just insert the new row, and if you care about ordering by the id, always use order by id in your queries.
You could use a calendar table based approach here:
INSERT INTO yourTable (id)
SELECT t1.id
FROM
(
SELECT 1 AS id UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
SELECT 4 UNION ALL SELECT 5
) t1
LEFT JOIN yourTable t2
ON t2.id = t1.id
WHERE
t1.id IS NULL;
In practice, you might replace the inlined subquery aliased as t1 above with a bona fide sequence table covering all id values which you would want to cover.

JOIN / UNION SELECT all rows from two tables with different number of columns

I am trying to join or union the results of two differently structured tables, order them by a their common pubdate column, but get an error message:
The used SELECT statements have a different number of columns
SELECT * FROM news WHERE published='1' AND image!='' AND featured='1'
JOIN
SELECT * FROM videos WHERE published='1'
ORDER BY pubdate DESC
How can I edit my query so that I can run my fetch array and retrieve the corresponding rows afterwards (the rows to be fetched is then decided on another common row that both tables share)?
You can UNION ALL tables with a different number of columns by adding the missing columns in the select list. I mean, suppose you have:
SQL> create table one ( c1 integer , c2 integer, c3 integer ) ;
SQL> create table two ( c1 integer , c2 integer ) ;
The following UNION ALL won't work:
SQL> select * from one union all select * from two ;
[mysqld-5.5.27]The used SELECT statements have a different number of columns
But this one is ok:
SQL> select * from one union all select *, null from two ;
Note we did add NULL for the missing (c3) column on table two. You can add whatever you want...
Since you not provided sample data, we can't suggest you correct way what and how to use, but I noticed that:
With JOIN you have incorrect syntax. Should be like:
SELECT *
FROM tbl1 t1
INNER JOIN tbl2 t2 ON t1.Id = t2.Id
If you want to use UNION - order of columns and number of columns should match in both tables, so you have to provide column names in both tables, in following:
SELECT Col1, Col2, Coln
FROM tbl1
UNION
SELECT Col1, Col2, Coln
FROM tbl2

SQL Join 2 tables with almost same field

I need to join two tables in SQL. There are no common fields. But the one table have a field with the value krin1001 and I need it to be joined with the row in the other table where the value is 1001.
The idea behind the joining is i have multiple customers, but in the one table there customer id is 'krin1001' 'krin1002' and so on, in this table is how much they have sold. In the other table there customer is is '1001' '1002' and so on, and in this table is there name and adress and so on. So it will always be the first 4 charakters i need to strip from the field before matching and joining. It might not always be 'krin' i need it to work with 'khjo1001' also, and it still needs to join on the '1001' value from the other table.
Is that possible?
Hope you can help me.
You need to use substring:
ON SUBSTRING(TableA.Field, 5, 4) = TableB.Field
Or Right:
ON RIGHT(TableA.Field, 4) = TableB.Field
You can also try to use CHARINDEX function for join operation. If value from table1 contains value from table2 row will be included in result set.
;WITH table1 AS(
SELECT 'krin1001' AS val
UNION ALL
SELECT 'xxx'
UNION ALL
SELECT 'xyz123'
),
table2 AS(
SELECT '1001' AS val
UNION ALL
SELECT '12345'
UNION ALL
SELECT '123'
)
SELECT * FROM table1 AS t
JOIN table2 AS T2 ON CHARINDEX(T2.val, T.val) > 0
Use it as:
SELECT
*
FROM table t1
INNER JOIN table t2 ON RIGHT(t1.col1, 4) = t2.col1;

Needs help in database query

I have two tables Table1 and Table2. There are 10 fields in Table1 and 9 fields in Table2. There is one common column in both the tables i.e. AdateTime. This column saves unix time stamp of user actions. I want to display records from both the tables as a single result but sorting must me according to AdateTime. Recent action should be display first. Sometimes many recent actions in Table1 but few in Table2. Vice versa is also possible. So I want to fetch combine result set from both the tables using single query. I am using PHP MySQL.
Try
SELECT t1.*, t2.*
FROM table1 t1 INNER JOIN table2 t2
ON t1.AdateTime = t2.AdateTime
ORDER BY t1.AdateTime
or (if tables are not related)
SELECT * FROM
(SELECT ADateTime, col1, col2, col3, col4 FROM table1
UNION
SELECT ADateTime, col1, col2, 1 AS col3, NULL AS col4 FROM table2) t2
ORDER by ADateTime
I would use UNION ALL with an inline view. So something like
select col1,col2,col3,col4,col5,col6,col7,col8,col9,AdateTime
from
(
select col1,col2,col3,col4,col5,col6,col7,col8,col9,AdateTime from Table1
UNION ALL
select col1,col2,col3,col4,col5,col6,col7,col8,null as col9,AdateTime from Table2
) t
order by t.Adatetime desc;
yes you can do it. you just need to join these 2 tables with a join condition. when the join condition matches for a row only that row ll be displayed then further you can write the Code for any operation. use order by AdateTime
select t1.column_1234,t2.column_1234
from t1 table1 , t2 table2
where t1.matching_column = t2.matching_column
order by t1.AdateTime;
t1.matching_column And t2.matching_column are the Primary And Foreign keys for these tables (Matching Column)