How to write such query? - mysql

How do you programming in SQL, I don't understand nothing in it. :)
Table1:
+-----------+----------+------------+
| id | key | page |
+-----------+----------+------------+
| 1 | A | 123 |
| 2 | B | 456 |
| 3 | C | 777 |
+-----------+----------+------------+
Table2:
+-----------+----------+------------+
| id | key | page |
+-----------+----------+------------+
| 1 | A | 123 |
| 2 | B | 456 |
| 3 | C | 111 |
+-----------+----------+------------+
I have 2 tables. We can see that they have fields with the same 'key' (A, B, C). How can I filter 'page' column's value which are differ in Table1 and Table2.
So, in page column:
123=123, 456=456, 777<>111 ==> I want such table as Result:
NEW Table:
+-----------+---------------------+---------------------+
| id | id & page_table1 | id & page_table2 |
+-----------+---------------------+---------------------+
| 1 | 3 777 | 3 111 |
+-----------+---------------------+---------------------+

#LukazSzozda's comment seems to be the right answer. But if you actually want exactly those three comments in the result, you can concatenate them with the concat function, like this
select a.id,
concat(a.id, ' ', a.page)
concat(b.id, ' ', b.page),
from Table1 a
join Table2 b
on a.id = b.id
and a.key = b.key
where a.page != b.page

Your query is not "such difficult". First you need to join both tables on key column and then filter using page column:
SELECT *
FROM tab1
JOIN tab2 ON tab1.`key` = tab2.`key`
WHERE tab1.page <> tab2.page;

If you want new table with new ID, you need to have create table. I recommend different format
CREATE TABLE newTable (
id INT AUTO_INCREMENT,
oldId int NOT NULL,
tbl1Page int,
tbl2Page int,
PRIMARY KEY (id))
INSERT INTO newTable (oldId, tbl1Page, tbl2Page)
SELECT t1.key, t1.Page, t2.Page
FROM tab1 t1 INNER JOIN
tab2 t2 ON t1.key = t2.key
WHERE t1.page <> t2.page
I don't recommend combining ID and Page (or any other 2 data pieces) into one column. You can always combine data when you query it. Read about data normalization
Select concat(f1, ' - ', f2) as combinedData . . .

Related

Conditionally delete last row in mysql

How do I conditionally delete the last row in a mysql table?
me/my_machine#17:26:57>cat create_tables.sql
CREATE DATABASE IF NOT EXISTS test_db;
USE test_db;
CREATE TABLE IF NOT EXISTS err_hist_table (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
cl INT NOT NULL,
usr VARCHAR(16),
fault_code VARCHAR(10));
INSERT INTO err_hist_table (cl,usr,fault_code) VALUES (1,'pA','A'), (2,'pA','NULL'),(3,'pC','B'),(4,'pB','NULL');
The above SQL commands create a table that is like this:
MySQL [test_db]> SELECT * FROM err_hist_table;
+----+----+------+------------+
| id | cl | usr | fault_code |
+----+----+------+------------+
| 1 | 1 | pA | A |
| 2 | 2 | pA | NULL |
| 3 | 3 | pC | B |
| 4 | 4 | pB | NULL |
+----+----+------+------------+
4 rows in set (0.00 sec)
Now I want to DELETE the last row (biggest value of id) only when the value of fault_code is NULL. If it is not NULL, I want to skip the delete.
To my sql-newbie eyes, it seems like there should be a simple something like:
SELECT * IF err_history_table.id=max(err_history_table) AND fault_code = 'NULL';
I could not find my answer on the mysql docs page. Is there a simple solution for something like this?
You can do it with a subquery that returns the row of the maximum id where you check the value of fault_code:
DELETE FROM err_hist_table
WHERE id = (
SELECT id FROM (
SELECT * FROM err_hist_table
ORDER BY id DESC LIMIT 1
) t
WHERE fault_code IS NULL
);
See the demo.
Results:
| id | cl | usr | fault_code |
| --- | --- | --- | ---------- |
| 1 | 1 | pA | A |
| 2 | 2 | pA | |
| 3 | 3 | pC | B |
I'm not totally sure if this is what you want, but it should work. If you have a recent version of MySQL you should be able to use sub-queries, like this:
DELETE FROM err_hist_table WHERE id = (SELECT MAX(id) FROM err_hist_table) AND fault_code IS NULL
Untested on your specific table of course. I would even suggest performing a SELECT first to verify it does what you expect.
It's worth mentioning that you can acheive the desired result using a single JOIN, without needing a sub-sub-query and in a way which seems to me both concise and readable:
DELETE e1 FROM err_hist_table e1
JOIN (
SELECT MAX(id) AS id
FROM err_hist_table
) e2 USING (id)
WHERE e1.fault_code = 'NULL'
More on the topic of using joins in a DELETE statement here: https://dev.mysql.com/doc/refman/8.0/en/delete.html#idm45306662494864

How do return all columns in Table A where an ID column is present in Table B which contains hundreds of ID columns

I understand how to check if Column ID in Table A is present in Table B Column X.
But is there a way to return all rows in Table A in which it does NOT match a single Identifier in Table B?
In reality, Table B contains hundreds of columns.
Table A:
+------------+------+--------+----------------+
| Title Name | ID | Region | Numeric Column |
+------------+------+--------+----------------+
| Sam | B021 | NA | 5.99 |
| Brook | B026 | EU | 5.99 |
| Harry | B032 | KOR | 10.99 |
+------------+------+--------+----------------+
Table B:
+------+-------+-------+
| SAM | BROOK | HARRY |
+------+-------+-------+
| B021 | B024 | B030 |
| 1 | B025 | B031 |
| 2 | 4 | |
| 3 | | |
+------+-------+-------+
So in this instance, I would like my query to SELECT Rows 2 & 3 in Table A.
Using a NOT EXISTS could work.
SELECT *
FROM TableA a
WHERE NOT EXISTS
(
SELECT 1
FROM TableB b
WHERE a.ID IN (b.SAM, b.BROOK, b.HARRY)
);
I would use the NOT IN function to where,
SELECT * FROM TABLE A
WHERE col_A NOT IN (SELECT col_A
FROM TABLE B)
This will return all the rows from TABLE A where the val of col_A is not in TABLE B col_A
Hope this is helpful!
I think that one way or another, you will need to enumerate the columns that you want to search.
I would go for the left join antipattern, that, allows you to (safely) use the in operator:
select ta.*
from tableA ta
left join tableB tb on ta.id in (tb.sam, tb.brook, tb.harry)
where coalesce(tb.sam, tb.brook, tb.harry) is null
If you have a column in tableB that is not null (say, column never_null), the where clause can be simplfied:
select ta.*
from tableA ta
left join tableB tb on ta.id in (tb.sam, tb.brook, tb.harry)
where tb.never_null is null
I think you are looking for.
UNION doesn't work
SO
SELECT *
FROM tablea
Where `ID` NOT IN (SELECT HARRY FROM tableb)
OR `ID` NOT IN ( SELECT SAM FROM tableb )
OR `ID` NOT IN (SELECT HARRY FROM tableb)
DBfiddle
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=333a6d2605f881299d888e774fd41c44

Join 2 tables and create a new row showing if table 2 exists in table 1

I have this two tables
Table 1
+-----------+----------+
| support_id| Name |
+-----------+----------+
| 1 | Name 1 |
| 2 | Name 2 |
+-----------+----------+
Table 2
+-----------+----------+
| school_id | support_id|
+-----------+----------+
| 2314 | 1 |
+-----------+----------+
Desire output
+-----------+----------+------------+
| school_id |support_id| has |
+-----------+----------+------------+
| 2314 | 1 | Yes |
| 2314 | 2 | No |
+-----------+----------+------------+
How can I add the third row telling me if table 2 is in table 1?
Thanks in advance!
What do you mean a table1 "is" in table2?
The field support_id is the same as the support_id in table 2?
Or the field or the school_id is the same?
You need a field to be the same in both tables in order to make a connection (Foreign Key), make a join and connect both tables.
Considering support_id to be the foreigh key (the value shared between both tables) you can use this select:
SELECT school_id, IF(support_id is not null, "Yes", "No") as Has
FROM table1 LEFT JOIN table2
ON table1.support_id = table2.support_id;
I'd use a left join and then a case expression to format the results:
SELECT t2.*, CASE WHEN t1.support_id IS NOT NULL THEN 'Yes' ELSE 'No' END
FROM t2
LEFT JOIN t1 ON t2.support_id = t1.support_id

SQL select with complex insert

I am trying to concatenate 2 tables into 1 table with 1 mysql command. I also want to concatenate a file path into one path in the new table. Any information would be helpful. Thank you.
Something like this :
INSERT INTO table3 VALUES (Location) SELECT "A.Loc_Path B._FilePath" FROM Table2 A INNER JOIN table1 B ON A._Loc_ID = B._Loc_ID
I would like to take Table 1 & 2 and create Table 3
Table 1
| ID | _FilePath | _Loc_ID |
| 1 | 001\yay\txt.html | 1 |
| 1 | 002\yay\txt.php | 2 |
Table 2
| _Loc_ID | Loc_Path |
| 1 | D:\documents\test\ |
| 2 | C:\Temp\test\ |
Table 3
| Id | Location |
| 1 | D:\documents\test\001\yay\txt.html |
| 2 | C:\Temp\test\002\yay\txt.php |
Use concat
INSERT INTO table3 (Location) SELECT concat (A.Loc_Path , B._FilePath)
FROM Table2 A INNER JOIN table1 B ON A._Loc_ID = B._Loc_ID
what you need is to use the concat function to concatenate the two columns:
INSERT INTO table3 VALUES (Location) SELECT CONCAT(A.Loc_Path, B._FilePath) FROM
Table2 A INNER JOIN table1 B ON A._Loc_ID = B._Loc_ID

MySQL query to select group of IDs from one table, depending on query on a second table

I am sure this would be easy to google if I knew the right words to use, but I've tried and not come up with anything: apologies if this is a common question on SO.
I have one table which lists a set of records which can be one of 4 types.
table_1:
+-------+------------+------+
| id | value | type |
+-------+------------+------+
| 1 | x | 1 |
| 2 | y | 1 |
| 3 | z | 2 |
| 4 | a | 3 |
+-------+------------+------+
I have another table which references the id of this table and stores data
table_2:
+-------+------------+------+
| id | table_1_id |value |
+-------+------------+------+
| 1 | 4 | A |
| 2 | 2 | B |
| 3 | 3 | C |
| 4 | 2 | D |
+-------+------------+------+
I want to write a query that effects:
"Find all the records from table 1 which are of type 1, take the id's of those records, and find all the records in table 2 where 'table_1_id' which match one of that set of ids."
In the above very oversimplified table example that would result in the query returning records with ids 2 and 4 in table 2
Sounds like your looking for IN:
select *
from table2
where table_1_id in (select id from table1 where type = 1)
Or perhaps you could JOIN the tables:
select t2.*
from table2 t2
join table1 t1 on t2.table_1_id = t1.id
where t1.type = 1
Joining the tables could result in duplicate records. Depends on your needs.
SELECT t1.value,t1.type,t2.value FROM table1 t1,table2 t2 WHERE t1.id = t2.table_1_id AND t1.type = 1;