perl - update from two databases - sql

i have two databases in mariadb and i want to update two databases,
#Connect to the database1.
my $db1 = DBI->connect("DBI:mysql:database=db1;host=ip",
"login", 'paswword',
{'RaiseError' => 1});
#Connect to the database2.
my $db2 = DBI->connect("DBI:mysql:database=db2;host=ip",
"login", 'password',
{'RaiseError' => 1});
this query not work
my $query3 = $db1->prepare("
UPDATE worldmap.worldmap_table t1
SET t1.severity = 1000
WHERE t1.host IN
(SELECT h.name
FROM host_inventory as i, hosts as h WHERE i.hostid=h.hostid and h.available=1)");
$query3->execute;
thanks for your response

Use a single connection. Reference tables using the db.table syntax.

Related

How to make multiple SELECT queries at once in PostgreSQL?

Update: See the "Update" section below for the latest.
I have been working with Knex.js to build SQL queries in Node.js, and have the following code. This code works on a sort of graph data model (nodes and links), where there is a links table which has everything (links link to links). Given this code, I am wondering how I can make it one query instead of one query per attribute which is how it is now. The getTableName() function returns a string_links table for string values, and <x>_links tables for the other datatypes, while the "basic" links table is just called links.
Essentially how this works is, first query the top level where the parent_id is equal to some "type" ID, say we are querying "user" objects, the type would be "user". So let instance = ... is getting all the instance links from this user type. Then we go through each field of a query (a query for now is just boolean-valued map, like { email: true, name: true }). For each field of the query, we make a query to find all those nodes, linked off the instance, as so-called property links.
There are two types of properties, but don't need to go into too much detail on that. Essentially there are complex properties with audit trails and simple properties without audit trails. That is what is meant by the interactive branch in the logic.
How can I make this into one SQL query? The SQL query it prints out for an example is like this:
select "id" from "links" where "parent_id" = '47c1956bz31330c' and "name" = 'link' limit 1
select "value" from "string_links" where "parent_id" = (select "value" from "links" where "parent_id" = '47c1956bz31330cv' and "name" = 'name' limit 1) and "name" = 'value' limit 1
select "value" from "text_links" where "parent_id" = (select "value" from "links" where "parent_id" = '47c1956bz31330cv' and "name" = 'website' limit 1) and "name" = 'value' limit 1
select "value" from "integer_links" where "parent_id" = (select "value" from "links" where "parent_id" = '47c1956bz31330cv' and "name" = 'revenue' limit 1) and "name" = 'value' limit 1
select "value" from "boolean_links" where "parent_id" = '47c1956bz31330' and "name" = 'verified' limit 1
The original Node.js for Knex.js is here, but really I'm just concerned with how to write this as one regular SQL query, and I can figure out how to make it in Knex.js from there:
async function selectInteractiveInstance(user, name, query) {
const type = model.types[name]
const typeId = await baseSchemaController.selectType(name)
let instance = await knex.from(`links`)
.select('id')
.where('parent_id', typeId)
.where('name', 'instance')
.first()
// { id: 123, props: { ... } }
instance.props = {}
for (let field in query) {
let data = query[field]
let attrSchema = type[field]
const tableName = baseSchemaController.getTableName(attrSchema.type)
if (attrSchema.interactive) {
const query1 = knex
.from(`links`)
.select('value')
.where('parent_id', instance.link)
.where('name', field)
.first()
const record = await knex
.from(tableName)
.select('value')
.where('home', query1)
.where('name', 'value')
.first()
if (record) {
instance.props[field] = record.value
}
} else {
const record = await knex
.from(tableName)
.select('value')
.where('parent_id', instance.id)
.where('name', field)
.first()
if (record) {
instance.props[field] = record.value
}
}
}
return instance
}
The reason for asking is because the number of queries of this function is equal to the number of properties on the object, and I would like to avoid that, but not really that great at SQL yet. I don't see a straightforward or clear path on how to make this into one query, or know if it's possible.
It's also an issue for the following reason. If I want to grab 100 links, and their "fields" (in the primitive link tables), such that the primitive link values match a certain value, then you need to query all field tables simultaneously to see if the query can be satisfied.
Update
I finally landed on a query that works in the optimistic case:
select
"x"."id" as "id",
"s1"."value" as "name",
"s2"."value" as "inc_id",
"s3"."value" as "website",
"s4"."value" as "revenue",
"s5"."value" as "verified"
from "links" as "x"
inner join "links" as "c1" on "c1"."parent_id" = "x"."id"
inner join "string_links" as "s1" on "s1"."parent_id" = "c1"."value"
inner join "links" as "c2" on "c2"."parent_id" = "x"."id"
inner join "string_links" as "s2" on "s2"."parent_id" = "c2"."value"
inner join "links" as "c3" on "c3"."parent_id" = "x"."id"
inner join "text_links" as "s3" on "s3"."parent_id" = "c3"."value"
inner join "links" as "c4" on "c4"."parent_id" = "x"."id"
inner join "integer_links" as "s4" on "s4"."parent_id" = "c4"."value"
inner join "boolean_links" as "s5" on "s5"."parent_id" = "x"."id"
where "x"."parent_id" = '47c1956bz31330'
and "x"."name" = 'link'
and "c1"."name" = 'name'
and "s1"."name" = 'value'
and "c2"."name" = 'inc_id'
and "s2"."name" = 'value'
and "c3"."name" = 'website'
and "s3"."name" = 'value'
and "c4"."name" = 'revenue'
and "s4"."name" = 'value'
and "s5"."name" = 'verified'
This returns an object similar to what I am looking for, joining the same table several times, along with the primitive tables.
However, if any of the values are not linked (are socalled "null" in this context), then the inner join will fail and it will return nothing. How can I still have it return a subset of the object properties, whatever it can find? Is there anything like optional inner joins or anything like that?
Use LEFT JOIN and move possibly unsatisfied predicates to ON clause. Kind of
select
"x"."id" as "id",
"s1"."value" as "name",
"s2"."value" as "inc_id",
"s3"."value" as "website",
"s4"."value" as "revenue",
"s5"."value" as "verified"
from "links" as "x"
left join "links" as "c1" on "c1"."parent_id" = "x"."id" and "c1"."name" = 'name'
left join "string_links" as "s1" on "s1"."parent_id" = "c1"."value" and "s1"."name" = 'value'
left join "links" as "c2" on "c2"."parent_id" = "x"."id" and "c2"."name" = 'inc_id'
left join "string_links" as "s2" on "s2"."parent_id" = "c2"."value" and "s2"."name" = 'value'
left join "links" as "c3" on "c3"."parent_id" = "x"."id" and "c3"."name" = 'website'
left join "text_links" as "s3" on "s3"."parent_id" = "c3"."value" and "s3"."name" = 'value'
left join "links" as "c4" on "c4"."parent_id" = "x"."id" and "c4"."name" = 'revenue'
left join "integer_links" as "s4" on "s4"."parent_id" = "c4"."value" and "s4"."name" = 'value'
left join "boolean_links" as "s5" on "s5"."parent_id" = "x"."id" and "s5"."name" = 'verified'
where "x"."parent_id" = '47c1956bz31330'
and "x"."name" = 'link'

TypeORM multiple on conditions for join clause

I am working on a project that uses TypeORM and PostgreSQL, I am trying to use the query builder to join on multiple conditions. Is there an easier/ more programmatic way to do this than having all the conditions within a string? For example, I want to build the following query to get friends for a user. In SQL this query looks like this (Note: inRel is short for incoming relationship and outRel is short for outgoing relationship)
-- SELECT FRIENDS FOR USER
select outRel."relatingToUserId"
from relationships outRel
inner join relationships inRel
on inRel."userId" = outRel."relatingToUserId"
and inRel."relatingToUserId" = outRel."userId"
and inRel."type" = 'FRIEND'
and outRel."type" = 'FRIEND'
where outRel."userId" = 'some_uuid_for_the_user';
In TypeORM I can accomplish the same result doing
const relationships = await this.createQueryBuilder()
.select('outRel.relatingToUserId')
.from(RelationshipEntity, 'outRel')
.innerJoin(
RelationshipEntity,
'inRel',
`
inRel.userId = outRel.relatingToUserId
AND inRel.relatingToUserId = outRel.userId
AND inRel.type = 'FRIEND'
AND inRel.type = outRel.type
`,
)
.where('outRel.userId = :userId', { userId })
.getMany();
However, I would expect that I should be able to do something more like
const relationships = await this.createQueryBuilder()
.select('outRel.relatingToUserId')
.from(RelationshipEntity, 'outRel')
.innerJoin(RelationshipEntity, 'inRel', 'inRel.userId = outRel.relatingToUserId')
.andWhere('inRel.relatingToUserId = outRel.userId')
.andWhere("inRel.type = 'FRIEND'")
.andWhere('inRel.type = outRel.type')
.where('outRel.userId = :userId', { userId })
.getMany();
But this does not return the same result. Is there a way to build this query more programmatically or am I stuck with a query string?
andWhere are used after .where. Try this:
const relationships = await this.createQueryBuilder()
.select('outRel.relatingToUserId')
.from(RelationshipEntity, 'outRel')
.innerJoin(RelationshipEntity, 'inRel', 'inRel.userId = outRel.relatingToUserId and inRel.relatingToUserId = outRel.userId and inRel.type = outRel.type')
.where('outRel.userId = :userId', { userId })
.andWhere('inRel.type = 'FRIEND'')
.getMany();

How to write join query with multiple column - LINQ

I have a situation where two tables should be joined with multiple columns with or condition. Here, I have a sample of sql query but i was not able to convert it into linq query.
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
This is how i have write linq query
await (from cm in Context.CustomerMaster
join li in list.PortalCustomerDetailViewModel
on new { OldNLKNo = cm.OldAcNo, NewNLKNo = cm.CustomerCode } equals new { OldNLKNo = li.OldNLKNo, NewNLKNo = li.NewNLKNo }
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
But this query doesn't returns as expected. How do I convert this sql query into linq.
Thank you
You didn't tell if list.PortalCustomerDetailViewModel is some information in the database, or in your local process. It seems that this is in your local process, your query will have to transfer it to the database (maybe that is why it is Tmp in your SQL?)
Requirement: give me all properties of a CustomerMaster for all CustomerMasters where exists at least one PortalCustomerDetailViewModel where
customerMaster.CustomerCode == portalCustomerDetailViewModel.NewNLKNo
|| customerMaster.OldAcNo == portalCustomerDetailViewModel.OldNLKNo
You can't use a normal Join, because a Join works with an AND, you want to work with OR
What you could do, is Select all CustomerMasters where there is any PortalCustomerDetailViewModel that fulfills the provided OR:
I only transfer those properties of list.PortalCustomerDetailViewModel to the database that I need to use in the OR expression:
var checkProperties = list.PortalCustomerDetailViewModel
.Select(portalCustomerDetail => new
{
NewNlkNo = portalCustomerDetail.NewNlkNo,
OldNLKNo = portalCustomerDetail.OldNLKNo,
});
var result = dbContext.CustomerMasters.Where(customerMaster =>
checkProperties.Where(checkProperty =>
customerMaster.CustomerCode == checkProperty.NewNLKNo
|| customerMaster.OldAcNo == checkProperty.OldNLKNo)).Any()))
.Select(customerMaster => new CustomerInfoViewModel
{
Id = customerMaster.Id,
Name = customerMaster.Name,
...
});
In words: from each portalCustomerDetail in list.PortalCustomerDetailViewModel, extract the properties NewNKLNo and OldNLKNo.
Then from the table of CustomerMasters, keep only those customerMasters that have at least one portalCustomerDetail with the properties as described in the OR statement.
From every remaining CustomerMasters, create one new CustomerInfoViewModel containing properties ...
select cm.* from Customer cm
inner join #temp tmp
on cm.CustomerCode = tmp.NewNLKNo or cm.OldAcNo = tmp.OldNLKNo
You don't have to use the join syntax. Adding the predicates in a where clause could get the same result. Try to use the following code:
await (from cm in Context.CustomerMaster
from li in list.PortalCustomerDetailViewModel
where cm.CustomerCode == li.NewNLKNo || cm.OldAcNo = li.OldNLKNo
select new CustomerInfoViewModel
{
CustomerId = cm.Id,
CustomerCode = cm.CustomerCode,
CustomerFullName = cm.CustomerFullName,
OldCustomerCode = cm.OldCustomerCode,
IsCorporateCustomer = cm.IsCorporateCustomer
}).ToListAsync();
var result=_db.Customer
.groupjoin(_db.#temp ,jc=>jc.CustomerCode,c=> c.NewNLKNo,(jc,c)=>{jc,c=c.firstordefault()})
.groupjoin(_db.#temp ,jc2=>jc2.OldAcNo,c2=> c2.OldNLKNo,(jc2,c2)=>{jc2,c2=c2.firstordefault()})
.select(x=> new{
//as you want
}).distinct().tolist();

Codeigniter Joining Tables - Passing Parameters

I'm attempting to join two tables while using codeigniter. I've done this same SQL query writing regular SQL. When I attempt to do the same in codeigniter, I keep getting errors. I'm not quite sure what I'm doing wrong. What do you guys think I'm doing wrong?
My function in model_data.php
function getJoinInformation($year,$make,$model)
{
//$this->db->distinct();
// here is where I need to conduct averages but lets just work on extracting info.
// from the database and join tables.
$this->db->select('*');
$this->db->from('tbl_car_description');
$this->db->join('tbl_car_description', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
/*
$query = $this->db->get_where('tbl_car_description',
array(
'year' => $year,
'make' => $make,
'model' => $model
)
);
if($query->num_rows()) return $query->result();
return null;
*/
}
My error message
A Database Error Occurred
Error Number: 1066
Not unique table/alias: 'tbl_car_description'
SELECT * FROM (`tbl_car_description`) JOIN `tbl_car_description` ON `d`.`id` = `p`.`cardescription_id` WHERE `d`.`year` = '2006' AND `d`.`make` = 'Subaru' AND `d`.`model` = 'Baja'
Filename: C:\wamp\www\_states\system\database\DB_driver.php
Line Number: 330
Here is the code written in SQL and it's working great. I want to do the something in codeigniter but I'm confused as to how. Any help would be much appreciated. Thanks everyone.
$sql_2 = mysql_query("SELECT ROUND(AVG(p.value),1) AS AvgPrice, ROUND(AVG(p.mileage),1) AS AvgMileage
FROM tbl_car_description d, tbl_car_prices p
WHERE (d.id = p.cardescription_id)
AND (d.year = '".$year."')
AND (d.make = '".$make."')
AND (d.model = '".$model."')
AND (p.approve = '1')");
Your CI query references the same table twice, which I assume is a typo. However, you only need include your table alias with the table name in your Active Record call:
//$this->db->distinct();
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
Couple issues: You need to include your table aliases and your join should have the name of the second table ...
$this->db->from('tbl_car_description AS d');
$this->db->join('tbl_car_prices AS p', 'd.id = p.cardescription_id');

How can I get a list of indices on a SQL table using Perl?

How can I get a list of the indices on a table in my sybase database using Perl? The goal is to "copy" all the indices from a table to a nearly identical table.
Is $dbh->selectarray_ref('sp_helpindex $table') the best I can do?
There's a statistics_info() method in DBI, but unfortunately, the only DBD I've seen it implemented in so far is DBD::ODBC . So if you use ODBC (update: or PostgreSQL!) you're in luck. Otherwise sp_helpindex (or the sysindexes table) is about as good as it gets for Sybase.
Here's what I've used for Sybase (in my own OO module - it returns only unique indexes unless the all_indexes argument is true):
{
my $sql_t = <<EOT;
select
sysindexes.name,
index_col(object_name(sysindexes.id), sysindexes.indid, syscolumns.colid) col_name
from sysindexes, syscolumns
where sysindexes.id = syscolumns.id
and syscolumns.colid <= sysindexes.keycnt
and sysindexes.id = object_id(%s)
EOT
sub index_info {
my ( $self, $table, $all_indexes ) = #_;
my $dbh = $self->{DBH};
my $sql = sprintf $sql_t, $dbh->quote($table);
$sql .= "and sysindexes.status & 2 = 2\n" unless $all_indexes;
my $sth = $dbh->prepare($sql);
$sth->execute();
my #col_names = #{$sth->{NAME_lc}};
my %row; $sth->bind_columns(\#row{#col_names});
my %ind;
while ($sth->fetch()) {
if ( $row{col_name} ) {
push #{$ind{$row{name}}}, lc($row{col_name});
}
}
return unless %ind;
return \%ind;
}
}
Or if your goal is to just copy indexes, maybe you should get the dbschema.pl utility (which uses Sybase::DBlib). It will generate the "CREATE INDEX" statements for you.
SELECT i.*
FROM sysobjects o, sysindexes i
WHERE o.name = $name
AND i.id = o.id