I have more than 50 tables that are not related but all of them have a "Name" field, I want to query "John" and get all Johns in the different tables and store each row in an array (Javascript) for example:
arr['table1']="results if any"
arr["table2"]="results if any".
What I'm doing right now is a for loop for each table:
SELECT * from tablesNameArray[i] WHERE name="John",
but I'm really wondering if there is any other better or "more" correct way to do it.
Thanks
You can do it in a single query using UNION:
SELECT * FROM table1 WHERE name = 'John'
UNION ALL
SELECT * FROM table2 WHERE name = 'John'
UNION ALL
SELECT * FROM table3 WHERE name = 'John'
...
You can construct the query dynamically from the array:
sql = tablesNameArray.map(table => `SELECT * FROM ${table} WHERE name = 'John'`).join(" SELECT ALL ");
You could use joins. See the join docs, MySQL in this case.
Something like this should do it:
SELECT table1.*, table2.*, table3.*
FROM table1
LEFT JOIN table2 ON table1.name = table2.name
LEFT JOIN table3 ON table1.name = table3.name
WHERE table1.name = "John";
A left join will still select from the first table even if the joined table doesn't have a matching row -- you'll get NULL in the second table's selected columns for those rows which didn't match.
However, depending on your requirements, this is possibly no good -- I believe it won't grab rows from table2 or table3 where there's no corresponding row for that user in table1.
As pointed out by #spencer7593 in a comment below, you should probably only do this if you're certain the name column is unique within each table, otherwise you could be generating some ridiculously huge result sets.
Related
I am trying to create a procedure that choose columns dynamically from two table. I have already hardcoded query which works fine.
#Existing query
create table mydb.result_table as
select
t1.id,
t1.name,
t1.place,
t1.product
t1.prize
t2.id,
t2.name,
t2.place,
t2.product,
t2.prize
from source_db.source_table t1
full outer join target_db_target_table t2 on
t1.id=t2.id and t1.name=t2.name
where t1.place<>t2.place
Now i need to create a procedure which basically select column dynamically from given table name and join both with given keys
so something like below
CREATE OR REPLACE PROCEDURE result(source_db varchar, source_table VARCHAR, targt_db varchar, target_table VARCHAR, key_join varchar<not sure can pass list>, filter_col varchar )
returns string not null
language javascript
as
$$
var query= `create table mydb.result_table as
select
t1.<all columns from source_db and source_table>
t2.<all columns from targt_db and target_table >
from <source_db and source_table> as t1
full outer join <target_db_target_table> as t2
on <key_join> where <t1.filter_col <> t2.filter_col>
`
return 'success';
$$;
i don't see example of selecting columns dynamically for this kind of use case.
Any solution to this?
You need to query the information schema for the list of columns in each table and use the result to dynamically build your SQL statement.
You also need to be aware of the same column name existing in multiple tables as you obviously can’t have the same column appearing multiple times in a table - so you’ll need to dynamically rename columns as appropriate
Just query the INFORMATION_SCHEMA.COLUMNS view to access the table's columns and then you can build your query dynamically:
https://docs.snowflake.com/en/sql-reference/info-schema/columns.html
I'm currently learning MySQL and have learned the INSERTO INTO statement and the INSERT INTO SELECT statement.
The INSERT INTO statement works like this:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
While the INSERT INTO SELECT works like this:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
What I'm trying to do is add new values while also adding values that I already have stored in another table.
con.query("INSERT INTO vehicles (vehicleType, vehicleModel, vehicleOwner, vehicleSpawnX, vehicleSpawnY, vehicleSpawnZ)")
From the query above, I already have the vehicleOwner value stored in another table, while the other ones I've just gotten.
How can I do this? Add a VALUES statement before SELECT?
I'm using SQL Workbench 8.0 and JavaScript. Also, all the values are NOT NULL, so I can't make two different queries, unless on the first one I add temporary values that I'll update on the second one.
What I want to replace:
vehicleType -> "players"
vehicleModel -> vehicleCreate.model
vehicleOwner -> playerID FROM players table
vehicleSpawnX -> pos.x
vehicleSpawnY -> pos.y
vehicleSpawnZ -> pos.z
Thanks!
It's not possible... But you can select data and store that on variables, then you will store it in another table
You would construct a query. Your data model is a bit hard to follow since you give no examples of the data or of what you really want to do.
So let me give a simpler example. Say, you have a table with two columns for two players and you want to put the ids into a table -- but using their names. The query would look like:
insert into pairs (playerId1, playerId2)
select p1.playerId, p2.playerId
from players p1 join
players p2
on p1.name = ? and p2.name = ?;
The ? are for parameter placeholders. I assume you know to aways use parameters when passing values into a query.
I have two tables - customer and order with one-to-many relationship. I want to retrieve in a single query all customer data and total value of his orders.
In raw SQL that would be something like this:
select customer.*, o.total from customer
inner join (select sum(value) as total, customer_id from
order group by customer_id) as o
on customer.id=i.customer_id
My question is - how to express this query in Sequelize without writing SQL? Is this even possible?
Try this:
const query = `
SELECT
table_a.table_a_id AS "table_a.table_a_id",
table_b.table_b_id AS "table_b.table_b_id"
FROM
table_a
LEFT JOIN
(SELECT * FROM table_b) AS table_b
ON
table_a.table_b_id = table_b.table_b_id
`;
const options = {
model: models.table_a,
mapToModel: true,
nest: true,
raw: true,
type: sequelize.QueryTypes.SELECT
};
let tableAs = await db.sequelize.query(query, options);
Please note that you need the alias in the select statements. Seems like Sequelize.js differentiates the tables by the dot in the name.
caution: this doesn't work if table_a and table_b has "one to many" relationship because table_bs must be array. This seems like just overwrite table_b without making it array.
Hi xersee first you want to create two tables customer and order in sequalize.js format
Then after summation of value column and customer_id column from table order put it into one table
Then after that just join the new table with customer table in ORM Style
Please refer below link it may be help for you.
How to make join querys using sequelize in nodejs
I found many PHP examples which use map and implode to structure their string...I'm using Node and Javascript and I think that might be the problem. I have an array of ids and I'm saving it like this:
[1, 2, 3, 4].join();
That's being stored and I'm trying to run a query:
SELECT sr.id, sr.name, sr.city FROM table1 AS sr
JOIN table2 AS st WHERE sr.city = st.city AND sr.id IN (st.ids);
So both tables have a column city, table2 having multiple records, table1 only has one. The 'ids' column is of type TEXT in table2. Problem is it's only returning the row with id 1. If I do this:
SELECT sr.id, sr.name, sr.city FROM table1 AS sr
JOIN table2 AS st WHERE sr.city = st.city AND sr.id IN (1,2);
I will get rows 1 and 2. What's causing the problem? I tried [1, 2, 3, 4].join(', '); and that didn't help. Any suggestions?
I'm using MySQL v5.7 so I have access to JSON functions...I should've used this in the first place. The solution which works as I wanted is:
SELECT sr.id, sr.name, sr.city FROM table1 AS sr
JOIN table2 AS st WHERE sr.city = st.city AND
JSON_SEARCH(st.ids, 'one', sr.id) IS NOT NULL;
Love the new JSON support feature...altho it comes with its caveats. For example, the ids in the array have to be strings, the ids cannot be int's. JSON_SEARCH kept on returning NULL for paths to the ids until I converted them to strings. Trial and error...
On my website I am trying to select 2 tables - tableB of which might be empty, so its not returning any results at all when tableB is empty. I hope I am explaining this properly. Any suggestions?
curatio.webdb.getAllTodoItems = function(renderFunc) {
var db = curatio.webdb.db;
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM tableA, tableB", [], renderFunc,
curatio.webdb.onError);
});
}
basically TableA has e.g. Name and Surname columns and TableB has e.g. Address details. But sometimes there is no address, and then I cannot get anything to display.
I need to basically ignore tableB if it's empty.
If tableA and tableB have the same schema, you can do something like this:
SELECT * FROM tableA
UNION
SELECT * FROM tableB
However, if they don't have the same schema, you will have to do something smarter to get the union to work.
Although your query doesn't hint at this, I still think you are probably looking for a LEFT JOIN, because I'm assuming you want to link data from two tables by a common value in a column from table B (known as the foreign key).
This query selects values of the first table, even when there's no matching data in the join table:
SELECT *
FROM `tableA` `a`
LEFT JOIN `tableB` `b`
ON `b`.`someReferenceColumnToTableA` = `a`.`theReferredColumn`
Again, this assumes you meant to join two tables by some common value, for instance:
person (table A):
- id
- name
phonenumber (table B):
- id
- person_id // this is the foreign key to table A that "links" the data
- phonenumber
If you were to use a regular JOIN (also known as INNER JOIN) then only rows are returned for when both tables have matching data.
What your original query did, however, was (implicitly) CROSS JOIN all data from both tables. Given your question edit, I hardly think this is what you were actually after.
What you are performing there is called a Cross-Product of those two tables. A cross-product is essentially every row of tableA with every row of tableB. Since tableB has no rows, the cross-product has no rows. If you want all rows of both tables, use 2 queries. I would recommend reading a basic SQL tutorial.
curatio.webdb.getAllTodoItems = function(renderFunc) {
var db = curatio.webdb.db;
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM tableA UNION ALL SELECT * FROM tableB", [], renderFunc,
curatio.webdb.onError);
});
}
It will best to explicitly use the column names in both select rather then using the *.