Select From 2 Table With ID AND ParentID - between

I have 2 table :
1.message
2.replaytomessage
tables have 2 same filed :
1.title
2.matn
in message store topic and in replaytomessage store replay to topic
replaytomessage link to message with parentmid filed
i want write search in both table for example i search 'test' , select query find in title & matn in message and replaytomessage
i write this query :
$result = mysql_query("SELECT * FROM message inner Join replaytomessage On message.mid = replaytomessage.parentmid WHERE message.matn LIKE '%$qfind%' OR message.title LIKE '%$qfind%' ORDER BY message.mid DESC LIMIT $start, $per_page") or die(mysql_error());
but in result show replaytomessage data or no correct title...
this is my While :
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo "<td width = '300'>";
$title = mysql_real_escape_string($row['title']);
$mid = intval($row['mid']);
$member = intval($row['member_id']);
echo "<a href = 'message.php?mid=$mid'>$title</a>";
echo "</td> ";
}

I haven't entirely understood what you are trying to achieve, but my suggestion would be to write the query in a database (MySQL?) client until you get the results you are expecting, and then translate into code (PHP?).
From what I think I understand, you need to give aliases to your columns to retrieve the correct data:
SELECT message.title as messagetitle, replaytomessage.title as replaytitle,
message.mid as messagemid, replaytomessage.mid as replaymid,
message.member_id as messagememberid, replaytomessage.member_id as replaymemberid
FROM message ...
then you can use the aliases to get the data from the table that you want

I have a ticket system with php/mysql , i want search in topics and answer top topic tables.
topic store in message table and answer to topic store in replaytomessage
for example when i searching 'test' word , i want show result from both table(message,replaytomessage) , maybe someone send topic Included 'test' word or someone answer to topic Included 'test' word.
I have 2 table : 1.message 2.replaytomessage
tables have 2 same filed : 1.title 2.matn
in message store topic and in replaytomessage store replay to topic data , replaytomessage link to message with parentmid filed
i dont know i must user UNION OR Join!

Related

Yii2: How to do a inner join of three tables?

I have a many-to-many relationship so I have three tables (administrators, offices and the intermediate table):
I need to do a very simple innerjoin of the three tables to show lastnames and their offices with Active Record. I tried but I couldn't.
This is what I tried:
$admins = Admins::find()
->joinWith(Oficinas::tableName())
->all();
echo '<pre>';
print_r($admins);
echo '</pre>';
die();
Also I would like to know how to show the SQL query so it can help me to find a solution.
You need to specify the relation name for joinWith() rather than table names. Since there isn't any info on the relation names I will use simple innerJoin using table names as per your requirements to display the last name and the office name for the admins.
Admins::find()
->alias('a')
->select('a.lastnameadm, o.nombreofi')
->innerJoin('admin_oficinas ao','ao.idadm = a.idadm')
->innerJoin('oficinas o','o.idofi = ao.idofi')
->all();
Try this:
TABLE_NAME_1::find()
->join('inner join',
'table_name_2',
'table_name_2.column = table_name_1.column'
);
->join('inner join',
'table_name_3',
'table_name_3.column = table_name_2.column'
)->all();
but if you can also use Via like the following example:
public function getClassschedule()
{
return $this->hasOne(TABLE_NAME_2::className(), ['table_name_1.column' => 'table_name_2.column'])
->via('tableName3');
}
when excuded, the results should be obtained like the previous example. so there's no need to repeated relations. full documentation can be seen here :
https://www.yiiframework.com/doc/guide/2.0/en/db-active-record

How is hyperledger composer playground implementing the "All Transactions"?

When I try to use a query for "org.hyperledger.composer.system.HistorianRecord" the results doesn't show the input for system transactions like AddAsset, AddParticipant, etc.
I want to create an audit trail for a single asset using queries.
There have been many questions about tracking the history of the asset, but I couldn't find a solution for this.
There must be a solution to this, hyperledger playground shows exactly how I would prefer in its "All Transaction" in the test section. So how can we code something to get same output as all transactions.
the query i used
query selectHistoricalRecord {
description: "Select all Historical Record of AddAsset"
statement:
SELECT org.hyperledger.composer.system.HistorianRecord
WHERE (transactionType == 'org.hyperledger.composer.system.AddAsset')
}
the logic.js for this
/**
* Remove all high volume commodities
* #param {org.example.trading.GetAssetHistory} tx - the asset for constructing audit trail
* #transaction
*/
async function GetAssetHistory(tx)
{
let results = await query('selectHistoricalRecord');
console.log( results );
}
the output is as:
but in all transaction:
we get something like this:
My questions is how is this "all transactions" showing the input, but historian doesn't. What other way can i get input for system transactions.
This query should get you the results:
query a2 {
description: "Select Transaction"
statement:
SELECT org.hyperledger.composer.system.AddAsset
}

Masterdata Services udpValidateModel Procedure

i've got a few tables in MDS.
One table (clients) ist filled via SQL and the other one is a masterdata table (country) filled by hand.
I have a business rule on table clients:
"Name must be unique" and no b-rule on Country.
I want to validate the data PROGRAMMATICALLY i do not want to CLICK "apply business rules" in explorer window on the webinterface.
I found several threads about how to use the sp mentioned in the title (udpValidateModel) to validate all entities in a model.
well...this thing does nothing. I can see the validationStatus in each of my tables "Awaiting Revalidation" after changing business rules or update data via sql. It doesnt matter what i do the status wont change (neither the validation icons in webui).
i also tried validateentity but the same "nothing" happens.
The SP below:
DECLARE #User_ID int
DECLARE #Model_ID int
DECLARE #Version_ID int
SET #User_ID = (SELECT ID FROM [MasterDataServices].[mdm].[tblUser] where userName = SYSTEM_USER )
SET #Model_ID = (SELECT Top 1 Model_Id FROM [MasterDataServices].[mdm].[viw_SYSTEM_SCHEMA_VERSION]
WHERE Model_MUID = 'MYMODELID')
SET #Version_ID = (SELECT Top 1 VersionNbr FROM [MasterDataServices].[mdm].[viw_SYSTEM_SCHEMA_VERSION]
WHERE Model_MUID = 'MYMODELID'
ORDER BY ID DESC )
EXECUTE [MasterDataServices].[mdm].[udpValidateModel] #User_ID, #Model_ID, #Version_ID, 1
Can anyone help?
SP 'udpValidateModel' works perfectly fine, looks like the parameters you are populating is not correct.
You may correct this as below and try; make sure that the system user has full authorization for the model.
SET #User_ID = (SELECT ID FROM [MasterDataServices].[mdm].[tblUser] where userName = SYSTEM_USER )
SET #Model_ID = (SELECT Top 1 Model_Id FROM [MasterDataServices].[mdm].[viw_SYSTEM_SCHEMA_VERSION]
WHERE Model_MUID = 'MYMODELID')
SET #Version_ID = (SELECT Top 1 VersionNbr FROM [MasterDataServices].[mdm].[viw_SYSTEM_SCHEMA_VERSION]
WHERE Model_MUID = #Model_ID
ORDER BY ID DESC )

Order by field from other table

I have 2 tables; user and user_info with their models User and UserInfo. user holds id, expire and user_info_id, while user_info holds id and username.
I'd like to get all users where expire is greater or less than $now or null, and I'd like to sort the list by username. This last part is where my problem lies.
What I currenty have;
$usersQ = User::where ('expire', '>', $now)->orWhereNull ('expire');
$usersCount = $usersQ->count ();
$users = $usersQ->get ();
I have tried;
$usersQ = User::with ('user_info')->join ('user_info', 'user.user_info_id', 'user_info.id')->where ('expire', '>', $now)->orWhereNull ('expire')->orderBy ('username');
Unfortunately, this didn't work (SQL syntax error).
Note: I do actually need User as my main entity rather than UserInfo because I need other information from User in my View.
Basically;
SELECT user.*, user_info.username, user_info.fname, user_info.lname
FROM user
INNER JOIN user_info ON user.user_info_id = user_info.id
ORDER BY user_info.username ASC;
And then I'd be able to get access to everything from user and those 3 fields from user_info. How on earth do I do that with Laravel?
$users = User::with('user_info')->where('expire', '>', $now)
->orWhereNull('expire')->get();
$usercount = $users->count();
Eloquent Relationships
Eager Loading
Ah, damn. Seems I got the order wrong.
$usersQ = User::join ('user_info', 'user_info.id', '=', 'user.user_info_id')->orderBy ($order)->where ('expire', '>', $now)->orWhereNull ('expire');
$usersCount = $usersQ->count ();
$users = $usersQ->get ();
This is working just fine, except for the bug in Laravel (yes, it's a bug in my opinion) that overwrites the value of any field with a duplicate name. Would be great if anyone knew a fix for that... Joins are pretty much useless if your id gets overwritten.

New Google Spreadsheets publish limitation

I am testing the new Google Spreadsheets as there is a new feature I really need: the 200 sheets limit has been lifted (more info here: https://support.google.com/drive/answer/3541068).
However, I can't publish a spreadsheet to CSV like you can in the old version. I go to 'File>Publish to the web' and there is no more options to publish 'all sheets' or certain sheets and you can't specify cell ranges to publish to CSV etc.
This limitation is not mentioned in the published 'Unsupported Features' documentation found at: https://support.google.com/drive/answer/3543688
Is there some other way this gets enabled or has it in fact been left out of the new version?
My use case is: we retrieve Bigquery results into the spreadsheets, we publish the sheets as a CSV automatically using the "publish automatically on update" feature which then produces the CSV URL which gets placed into charting tools that read the CSV URL to generate the visuals.
Does anyone know how to do this?
The new Google spreadsheets use a different URL (just copy your <KEY>):
New sheet : https://docs.google.com/spreadsheets/d/<KEY>/pubhtml
CSV file : https://docs.google.com/spreadsheets/d/<KEY>/export?gid=<GUID>&format=csv
The GUID of your spreadsheet relates to the tab number.
/!\ You have to share your document using the Anyone with the link setting.
Here is the solution, just write it like this:
https://docs.google.com/spreadsheets/d/<KEY>/export?format=csv&id=<KEY>
I know it's weird to write the KEY twice, but it works perfectly. A teammate from work discovered this by opening the excel file in Google Docs, then File -> Download as -> Comma separated values. Then, in the downloads section of the browser appears a link to the CSV file, like this:
https://docs.google.com/spreadsheets/d/<KEY>/export?format=csv&id=<KEY>&gid=<SOME NUMBER>
But it doesn't work in this format, what my friend did was remove "&gid=<SOME NUMBER>" and it worked! Hope it helps everyone.
If you enable "Anyone with the link sharing" for spreadsheet, here is a simple method to get range of cells or columns (or whatever your feel like) export in format of HTML, CSV, XML, JSON via the query:
https://docs.google.com/spreadsheet/tq?key=YOUR-KEY&gid=1&tq=select%20A,%20B&tqx=reqId:1;out:html;%20responseHandler:webQuery
For tq variable read query language reference.
For tqx variable read request format reference.
Downside to this is that your doc is still availble in full via the public link, but if you want to export/import data to say Excel this is a perfect way.
It's not going to help everyone, but I've made a PHP script to read the HTML into an array.
I've added converting back to a CSV at the end. Hopefully this will help some people who have access to PHP.
$html_link = "https://docs.google.com/spreadsheets/d/XXXXXXXXXX/pubhtml";
$local_html = "sheets.html";
$file_contents = file_get_contents($html_link);
file_put_contents($local_html,$file_contents);
$dom = new DOMDocument();
$html = #$dom->loadHTMLFile($local_html); //Added a # to hide warnings - you might remove this when testing
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(0)->getElementsByTagName('tr');
$cols = $rows->item(0)->getElementsByTagName('td'); //You'll need to edit the (0) to reflect the row that your headers are in.
$row_headers = array();
foreach ($cols as $i => $node) {
if($i > 0 ) $row_headers[] = $node->textContent;
}
foreach ($rows as $i => $row){
if($i == 0 ) continue;
$cols = $row->getElementsByTagName('td');
$row = array();
foreach ($cols as $j => $node) {
$row[$row_headers[$j]] = $node->textContent;
}
$table[] = $row;
}
//Convert to csv
$csv = "";
foreach($table as $row_index => $row_details){
$comma = false;
foreach($row_details as $value){
$value_quotes = str_replace('"', '""', $value);
$csv .= ($comma ? "," : "") . ( strpos($value,",")===false ? $value_quotes : '"'.$value_quotes.'"' );
$comma = true;
}
$csv .= "\r\n";
}
//Save to a file and/or output
file_put_contents("result.csv",$csv);
print $csv;
Here is another temporary, non-PHP workaround:
Go to an existing NEW google sheet
Go to "File -> New -> Spreadsheet"
Under "File -> Publish to the web..." now has the option to publish a csv version
I believe this is actually creating an old Google sheet but for my purposes (importing google sheet data from clients or myself into R for statistical analysis) it works until they hopefully update this feature.
I posted this in a Google Groups forum also, please find it here:
https://productforums.google.com/forum/#!topic/docs/An-nZtjaupU
The correct URL for downloading a Google spreadsheet as CSV is:
https://docs.google.com/spreadsheets/export?id=<ID>&exportFormat=csv
The current answers do not work anylonger. The following has worked for me:
Do File -> "Publish to the web" and select 'start publishing' and the format. I choose text (which is TSV)
Now just copy the URL there which will be similar to https://docs.google.com/spreadsheet/pub?key=YOUR_KEY&single=true&gid=0&output=txt
That new feature appears to have disappeared. I don't see any option to publish a csv/tsv version. I can download tsv/csv with the export, but that's not available to other people with merely the link (it redirects them to a google docs sign-in form).
I found a fix! So I discovered that old spreadsheets before this change were still allowing only publishing certain sheets. So I made a copy of an old spreadsheet, cleared the data out, copy and pasted my current info into it and now I'm happily publishing just a single sheet of my large spreadsheet. Yay
I was able to implement a query to the result, see this table
https://docs.google.com/spreadsheets/d/1LhGp12rwqosRHl-_N_N8eTjTwfFsHHIBHUFMMyhLaaY/gviz/tq?tq=select+A,B,I,J,K+where+B%3E=4.5&pli=1
the spreadsheet fetches data from earthquake, but I just want to select MAG 4.5+ earthquakes so it makes the query and the columns, just a problem:
I cannot parse the result, I tried to decode as json but was not able to parse it.
I would like to be able to show this as HTML or CSV or how to parse this ? for example to be able to plot it on a Google Map.

Resources